258 lines
13 KiB
Python
258 lines
13 KiB
Python
#!/usr/bin/env python3
|
||
"""端到端(打真接口、真流程):同一张单,办结前后手机端摆内容那两份配置不许换。
|
||
|
||
守的是 2026-11-16 这一寸:手机端审批那一屏读的是"此刻"那份配置(``forms_live`` /
|
||
``activity_perms_live``),从前后端只给在途单算这两份,单子一办结就断档,同一屏当场
|
||
换一副面孔。这里照界面上真走的那条路跑一遍:设计接口改表单 + 改环节字段权限(顺带验
|
||
进程内那层快照当场作废、办结件也照样"保存即见效"),再一步步把这张单办到落定,
|
||
比对办结前后那两份报文。
|
||
|
||
cd backend && PYTHONPATH=. python3 scripts/e2e_mobile_parity.py
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import contextlib
|
||
import os
|
||
import pathlib
|
||
import sys
|
||
from datetime import datetime
|
||
|
||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent))
|
||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
||
# TestClient 会跑一遍应用启动:不关掉调度线程,超时标记与写回投递会在断言中间自己动
|
||
os.environ.setdefault("OA_SCHEDULER", "off")
|
||
|
||
from sqlalchemy import select # noqa: E402
|
||
from starlette.testclient import TestClient # noqa: E402
|
||
|
||
from app import models # noqa: E402
|
||
from app.db import SessionLocal # noqa: E402
|
||
from app.main import app # noqa: E402
|
||
from app.security import create_access_token # noqa: E402
|
||
from check_write_payload import purge # noqa: E402
|
||
|
||
PROCESS_NAME = "备用金申请流程"
|
||
DATA = {
|
||
"loanType": "personalLoan", "loanReason": "办结前后一致性校验",
|
||
"loanItems": [{"loanNote": "校验", "loanType": "personalLoan", "loanTypeName": "校验",
|
||
"loanAmount": 1000, "returnDate": "2099-12-31"}],
|
||
"loanAmountTotal": 1000,
|
||
"payItems": [{"payee": "康文靖", "bankName": "校验银行", "bankAccount": "6222020200009999",
|
||
"payAmount": 1000, "payWay": "bank"}],
|
||
}
|
||
STAMP = datetime.now().strftime("%m%d%H%M%S")
|
||
TITLE = f"办结一致性校验单 {STAMP}"
|
||
LIVE_KEY = "e2eLiveField"
|
||
|
||
FAILS: list[str] = []
|
||
PASSED = 0
|
||
|
||
|
||
def check(label: str, passed: bool, detail: str = "") -> bool:
|
||
global PASSED
|
||
if passed:
|
||
PASSED += 1
|
||
print(f"[通过] {label}")
|
||
else:
|
||
FAILS.append(label)
|
||
print(f"[FAIL] {label}" + (f" -> {detail}" if detail else ""))
|
||
return passed
|
||
|
||
|
||
class Api:
|
||
"""薄壳:把一次接口调用折成 ``(status, data, message)``。"""
|
||
|
||
def __init__(self) -> None:
|
||
self._client = TestClient(app, raise_server_exceptions=False)
|
||
|
||
@staticmethod
|
||
def token(person: models.User) -> str:
|
||
return create_access_token(str(person.id))[0]
|
||
|
||
def call(self, method: str, path: str, *, token: str, json: dict | None = None):
|
||
response = self._client.request(
|
||
method, f"/api/v1{path}",
|
||
headers={"Authorization": f"Bearer {token}"}, json=json)
|
||
with contextlib.suppress(ValueError):
|
||
body = response.json()
|
||
if isinstance(body, dict):
|
||
return response.status_code, body.get("data"), str(body.get("message") or "")
|
||
return response.status_code, None, ""
|
||
|
||
def post(self, path, *, token, json=None):
|
||
return self.call("POST", path, token=token, json=json)
|
||
|
||
def put(self, path, *, token, json=None):
|
||
return self.call("PUT", path, token=token, json=json)
|
||
|
||
def get(self, path, *, token):
|
||
return self.call("GET", path, token=token)
|
||
|
||
|
||
def design_routes(db: SessionLocal, process_id: str) -> list[dict]:
|
||
"""整图保存要的那份路由载荷(逐字段照模型那一行抄,别自己发明键名)。"""
|
||
return [{
|
||
"id": row.id, "name": row.name, "alias": row.alias or "",
|
||
"from_activity": row.from_activity, "to_activity": row.to_activity,
|
||
"expression": row.expression or "", "decision": row.decision or "",
|
||
"order_number": int(row.order_number or 0),
|
||
} for row in db.execute(select(models.Route).where(models.Route.process == process_id)
|
||
.order_by(models.Route.order_number)).scalars().all()]
|
||
|
||
|
||
def fields_of(payload: dict) -> list[str]:
|
||
content = ((payload.get("forms") or [{}])[0].get("content") or {})
|
||
return [str(item.get("key")) for item in content.get("fields") or [] if isinstance(item, dict)]
|
||
|
||
|
||
def main() -> int:
|
||
api = Api()
|
||
db = SessionLocal()
|
||
person = db.execute(select(models.User).where(models.User.role == models.ROLE_ADMIN)).scalar_one()
|
||
tok = api.token(person)
|
||
jobs: list[str] = []
|
||
try:
|
||
process = db.execute(select(models.Process).where(models.Process.name == PROCESS_NAME)
|
||
).scalars().first()
|
||
if process is None:
|
||
return check(f"素材:库里有「{PROCESS_NAME}」", False) and 1
|
||
form = db.get(models.FormElement, process.latest_form)
|
||
if form is None:
|
||
return check("素材:这个流程挂着表单", False) and 1
|
||
|
||
# 设计改动前整份抄一份,收尾**逐字**递回去:从前收尾是"把这一格从 formPerms 里删掉",
|
||
# 而这一格本来就在配置里压着别的意思(生产上 loanReason 是 readonly),删掉就是
|
||
# 拿校验改坏真配置。整图保存认的是这一份载荷,载荷照原样就是照原样。
|
||
origin_rows = db.execute(select(models.Activity).where(models.Activity.process == process.id)
|
||
.order_by(models.Activity.order_number)).scalars().all()
|
||
origin_activities = [{
|
||
"id": row.id, "name": row.name, "type": row.type, "alias": row.alias or "",
|
||
"form": row.form or "", "description": row.description or "",
|
||
"config": dict(row.config or {}), "x": float(row.x or 0), "y": float(row.y or 0),
|
||
"order_number": int(row.order_number or 0),
|
||
} for row in origin_rows]
|
||
origin_routes = design_routes(db, process.id)
|
||
origin_form_content = dict(form.content or {})
|
||
origin_latest_form = process.latest_form or ""
|
||
|
||
# ---- 发起 -----------------------------------------------------------------
|
||
status, created, msg = api.post("/job", token=tok,
|
||
json={"process": process.id, "data": DATA, "title": TITLE})
|
||
if not check("发起一张单", status == 200 and bool((created or {}).get("job")), f"{status} {msg}"):
|
||
return 1
|
||
job, work_id = str(created["job"]), str(created.get("work") or created["id"])
|
||
jobs.append(job)
|
||
|
||
status, detail, msg = api.get(f"/job/{job}", token=tok)
|
||
activity = (detail or {}).get("task", {}).get("activity") or (detail or {}).get("activity")
|
||
if not check("在途单详情认得出当前那一环", bool(activity), str(msg)):
|
||
return 1
|
||
|
||
# ---- 改配置:表单加一格 + 当前那一环把 loanReason 按住 ------------------------
|
||
content = dict(form.content or {})
|
||
content["fields"] = list(content.get("fields") or []) + [
|
||
{"key": LIVE_KEY, "label": "校验新格", "type": "text"}]
|
||
status, _, msg = api.put(f"/process/forms/{form.id}", token=tok,
|
||
json={"name": form.name, "alias": form.alias or "",
|
||
"description": form.description or "",
|
||
"content": content, "editable": form.editable})
|
||
if not check("设计接口改表单(加一格)", status == 200, f"{status} {msg}"):
|
||
return 1
|
||
|
||
# 环节字段权限走整图保存:只改这一环的 config,其余原样递回去
|
||
activities = db.execute(select(models.Activity).where(models.Activity.process == process.id)
|
||
.order_by(models.Activity.order_number)).scalars().all()
|
||
body_activities = []
|
||
for row in activities:
|
||
config = dict(row.config or {})
|
||
if row.id == activity:
|
||
config["formPerms"] = {**(config.get("formPerms") or {}), "loanReason": "hidden"}
|
||
body_activities.append({"id": row.id, "name": row.name, "type": row.type,
|
||
"alias": row.alias or "", "form": row.form or "",
|
||
"description": row.description or "", "config": config,
|
||
"x": float(row.x or 0), "y": float(row.y or 0),
|
||
"order_number": int(row.order_number or 0)})
|
||
status, _, msg = api.put(f"/process/processes/{process.id}/design", token=tok, json={
|
||
"activities": body_activities,
|
||
"routes": design_routes(db, process.id),
|
||
"latest_form": process.latest_form or "",
|
||
})
|
||
if not check("设计接口改环节字段权限(loanReason → 隐藏)", status == 200, f"{status} {msg}"):
|
||
return 1
|
||
|
||
# ---- 办结之前:审批那一屏跟得到 ---------------------------------------------
|
||
status, running, msg = api.get(f"/job/{job}", token=tok)
|
||
running = running or {}
|
||
live_form = (running.get("forms_live") or {}).get(form.id) or {}
|
||
check("在途(审批那一屏)跟得到此刻那份表单:新格在里面",
|
||
LIVE_KEY in [str(item.get("key")) for item in live_form.get("fields") or []],
|
||
str(list(live_form)))
|
||
check("在途(审批那一屏)跟得到此刻那份字段权限:loanReason 按住",
|
||
((running.get("activity_perms_live") or {}).get(activity) or {}).get("loanReason") == "hidden",
|
||
str(running.get("activity_perms_live")))
|
||
|
||
# ---- 一路办到落定 ------------------------------------------------------------
|
||
guard = 0
|
||
while guard < 20:
|
||
guard += 1
|
||
status, detail, msg = api.get(f"/job/{job}", token=tok)
|
||
tasks = (detail or {}).get("tasks") or []
|
||
if not tasks:
|
||
break
|
||
task = tasks[0]
|
||
status, tdetail, msg = api.get(f"/task/{task['id']}", token=tok)
|
||
tdetail = tdetail or {}
|
||
guards = tdetail.get("route_guards") or {}
|
||
# 报文里的 routes 是整张图的,只挑从当前这一环出发的几条
|
||
name = next((r["name"] for r in (tdetail.get("routes") or [])
|
||
if r.get("from") == task.get("activity") and guards.get(r["id"], True)), "")
|
||
if not name:
|
||
check(f"环节「{task.get('activity_name')}」此刻有走得通的出口", False, str(guards))
|
||
break
|
||
status, _, msg = api.post(f"/task/{task['id']}/execute", token=tok,
|
||
json={"route_name": name, "opinion": "校验办结", "data": {}})
|
||
if status != 200:
|
||
check(f"办下去({name})", False, f"{status} {msg}")
|
||
break
|
||
|
||
# ---- 办结之后:不许换脸 -------------------------------------------------------
|
||
status, archived, msg = api.get(f"/work/{work_id}", token=tok)
|
||
archived = archived or {}
|
||
if not check("办结之后单据详情打得开", status == 200 and archived.get("status") != "running",
|
||
f"{status} {msg} / status={archived.get('status')}"):
|
||
return 1
|
||
archived_live = (archived.get("forms_live") or {}).get(form.id) or {}
|
||
check("办结之后手机端仍跟此刻那份表单(从前这里空着,一办结就换脸)",
|
||
LIVE_KEY in [str(item.get("key")) for item in archived_live.get("fields") or []],
|
||
str(archived.get("forms_live")))
|
||
check("办结之后仍带得出那一环此刻的字段权限",
|
||
((archived.get("activity_perms_live") or {}).get(activity) or {}).get("loanReason") == "hidden",
|
||
str(archived.get("activity_perms_live")))
|
||
check("凭证那一寸没被带跑:forms 出自查照(桌面 / 打印 / 引擎读它)",
|
||
LIVE_KEY not in fields_of(archived), str(fields_of(archived)))
|
||
check("凭证那一寸没被带跑:环节简报里那份 form_perms 仍是发起那一刻的",
|
||
((archived.get("activity_nodes") or {}).get(activity) or {}).get("form_perms", {})
|
||
.get("loanReason") != "hidden",
|
||
str(((archived.get("activity_nodes") or {}).get(activity) or {}).get("form_perms")))
|
||
finally:
|
||
# 设计与表单逐字还原,别让下一次跑撞上残留,也不许把校验没动过的那几格带走
|
||
restore_form = dict(origin_form_content)
|
||
api.put(f"/process/forms/{form.id}", token=tok,
|
||
json={"name": form.name, "alias": form.alias or "",
|
||
"description": form.description or "",
|
||
"content": restore_form, "editable": form.editable})
|
||
api.put(f"/process/processes/{process.id}/design", token=tok, json={
|
||
"activities": origin_activities, "routes": origin_routes,
|
||
"latest_form": origin_latest_form,
|
||
})
|
||
db.expire_all()
|
||
purge(db, jobs, [TITLE])
|
||
db.close()
|
||
|
||
print(f"\n共 {PASSED + len(FAILS)} 项,通过 {PASSED},失败 {len(FAILS)}")
|
||
return 1 if FAILS else 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
raise SystemExit(main())
|