unis-oa/backend/scripts/check_option_route_fill.py

404 lines
21 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#!/usr/bin/env python3
"""候选路由自带的带出(``optionRoutes[].fill``)的验收:不打真上游,内存库。
PYTHONPATH=. python3 scripts/check_option_route_fill.py
用户那一句:「**一个组件中为什么不能配置多个外部数据源、数据字典,我通过表单中字段来判断
该用什么数据源,并且可以获取到数据带出写入其他字段。**」 条件路由那层已经让一格挂多家候选,
但「带出」以前只住在字段自己那份 ``fetch`` 里——多挂一家就得再写一条取数条目、把同一个触发
条件抄第二遍,抄漏一处就是「候选换了家、带出还是上一家的」。这一层把带出挂到**那一条路由上**:
命中哪一条,就用哪一张源、那一条的入参、那一条的带出去向(口径 docs/option-source-routing-design.md)。
下面几件事必须一直成立:
1. **只有一份判据**:命中哪一条、按哪一条取候选、按哪一条带出,三处是同一个结果;
前端镜像 ``utils/formFetch.fetchConfigOf`` 与这里 :func:`fetch.config_of` 算出同一份;
2. **跑的还是那一个执行器**:入参写法、多源、留痕、``onError``、发起后冻结都不新发明,
只是多一个「只写带出去向」的记号——**这一格自己那一个值是人从候选里挑的,不许被盖**;
3. **回落不破**:一条都不成立、或命中的那条没自带带出,读的就是字段上那份 ``fetch``
(老表单一个字节不用改);
4. **保存那一刻洗得干净**:只留 ``source`` / ``args`` / ``picks`` / ``extras``,
空壳整块抹掉,换一种来源时这份带出当残骸清掉;
5. **设计期逐条体检**:带出去向那一格还在不在、带出的键在不在源声明的清单里、
入参引用掉没掉在地上,门牌写「第 N 条候选来源的带出」,不与字段自己那一份串。
"""
from __future__ import annotations
import pathlib
import re
import sys
from urllib.parse import parse_qs, urlparse
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent))
from sqlalchemy import create_engine, event # noqa: E402
from sqlalchemy.orm import Session # noqa: E402
from sqlalchemy.pool import StaticPool # noqa: E402
from app import cache as shared_cache, models # noqa: E402
from app.service import dicts, fetch, formruntime # noqa: E402
PASSED = 0
FAILS: list[str] = []
SENT: list[dict] = []
#: 每个供应商对应的开户行与额度:一行一个答案,才看得出问的是哪一家
#: 两家取值的源各答自己那一份:问的是哪一家、带的是哪个供应商,凑一起才有答案
ANSWERS = {
("erp_bank", "V1"): ("中国银行总行", "50000"),
("crm_bank", "V2"): ("招商银行分行", "8000"),
}
TRAVEL = {"match": "all", "rules": [{"field": "expenseType", "op": "eq", "value": "travel"}]}
KEYS = {"expenseType", "vendor", "dept", "bankName", "creditLimit"}
def eq(name: str, got, want) -> None:
global PASSED
if got == want:
PASSED += 1
print(f"[通过] {name}")
else:
FAILS.append(name)
print(f"[FAIL] {name} -> 期望 {want!r},实得 {got!r}")
def ok(name: str, condition, detail=None) -> None:
global PASSED
if condition:
PASSED += 1
print(f"[通过] {name}")
else:
FAILS.append(name)
print(f"[FAIL] {name} -> {detail if detail is not None else '条件不成立'}")
def new_session() -> Session:
for table in models.Base.metadata.tables.values():
for column in table.columns:
if column.server_default is not None:
column.server_default = None
engine = create_engine("sqlite://", poolclass=StaticPool, connect_args={"check_same_thread": False})
@event.listens_for(engine, "before_cursor_execute")
def _noop(conn, cursor, statement, parameters, context, executemany): # noqa: ANN001
pass
models.Base.metadata.create_all(engine)
return Session(engine)
def seed(db: Session) -> None:
"""两家给候选清单的列表型源 + 两家查开户行的取值型源(候选与带出各问一家,最常见那种)。"""
for code in ("erp_vendors", "crm_vendors"):
db.add(models.DataSource(
id=code, code=code, name=f"候选路由带出校验·{code}", system="ERP",
kind=models.DataSource.KIND_SEARCH, provider=models.DataSource.PROVIDER_HTTP,
enabled=True, method="GET", url="https://" + code + ".invalid/api/vendors?dept={arg.dept}",
headers={}, body_template={}, pick="data.rows", map_value="code", map_label="name",
map_extra={}, auth_type=models.DataSource.AUTH_NONE,
cache_seconds=0, timeout_seconds=5, retries=0,
))
for code in ("erp_bank", "crm_bank"):
db.add(models.DataSource(
id=code, code=code, name=f"候选路由带出校验·{code}", system="ERP",
kind=models.DataSource.KIND_FETCH, provider=models.DataSource.PROVIDER_HTTP,
enabled=True, method="GET", url="https://" + code + ".invalid/api/bank?code={arg.code}",
headers={}, body_template={}, pick="data.bank",
map_extra={"bank": "data.bank", "limit": "data.limit"},
auth_type=models.DataSource.AUTH_NONE,
cache_seconds=0, timeout_seconds=5, retries=0,
))
db.commit()
def fake_http(method, url, body, headers, timeout): # noqa: ANN001
parts = parse_qs(urlparse(url).query)
asked = urlparse(url).hostname.split(".")[0] # 问的是哪一家
code = (parts.get("code") or [""])[0] # 取值型那一家带的是哪个供应商
SENT.append({"source": asked, "code": code})
row = ANSWERS.get((asked, code))
if row is None:
return (404, '{"code":404,"message":"没有这个供应商"}')
return (200, '{"code":0,"data":{"bank":"%s","limit":"%s"}}' % row)
def routed(*, own: bool = False, on_error: str = "keep") -> list[dict]:
"""一格「供应商」:差旅问 ERP 那份清单,其余回落 CRM 那份;命中那条自带一份带出。
候选问列表型源(``erp_vendors``),带出问取值型源(``erp_bank``)——「刚选中那一行的
其它列」本来就常常在另一家,这份夹具顺手把那条路也验了。``own=True`` 时字段自己也配
一份 ``fetch``,回落那条路才验得动。
"""
field: dict = {
"key": "vendor",
"label": "供应商",
"type": "picker",
"optionSource": "dataSource",
"dataSourceCode": "crm_vendors",
"optionRoutes": [
{"source": "dataSource", "when": TRAVEL, "dataSourceCode": "erp_vendors",
"dataSourceArgs": {"dept": "{form.dept}"},
"fill": {"source": "erp_bank", "args": {"code": "{form.vendor}"},
"picks": {"bank": "bankName", "limit": "creditLimit"}}},
],
}
if own:
field["fetch"] = {"source": "crm_bank", "args": {"code": "{form.vendor}"},
"picks": {"bank": "bankName"}, "onError": on_error}
else:
field["fetch"] = None
return [
field,
{"key": "expenseType", "label": "费用类型", "type": "select",
"options": [{"value": "travel", "label": "差旅"}, {"value": "meet", "label": "招待"}]},
{"key": "dept", "label": "部门", "type": "text"},
{"key": "bankName", "label": "开户银行", "type": "text"},
{"key": "creditLimit", "label": "信用额度", "type": "text"},
]
def apply(db: Session, fields: list[dict], data: dict) -> dict:
"""走一遍提交链路里那一趟外部取数(与真机同一句 ``apply_form``)。"""
fetch.apply_form(db, fields, data, actor="tester")
return data
# ---------------------------------------------------------------------------
# 1. 合成:命中哪一条,就按那一条带出
# ---------------------------------------------------------------------------
def check_compose() -> None:
field = routed()[0]
hit = fetch.config_of(field, {"expenseType": "travel", "vendor": "V1"})
ok("命中差旅那条时用的是它那一份带出", hit is not None and hit.get("source") == "erp_bank", hit)
eq("带出只写别的格子", hit.get(fetch.FILL_ONLY_KEY), True)
eq("带出去向跟着那一条", hit.get("picks"), {"bank": "bankName", "limit": "creditLimit"})
eq("带出入参用这一条自己那份", hit.get("args"), {"code": "{form.vendor}"})
shared = {"key": "vendor", "type": "picker", "optionSource": "dataSource", "dataSourceCode": "crm_vendors",
"optionRoutes": [{"source": "dataSource", "when": TRAVEL, "dataSourceCode": "erp_vendors",
"dataSourceArgs": {"dept": "{form.dept}"},
"fill": {"picks": {"bank": "bankName"}}}]}
eq("带出没另写入参时沿用这一条筛候选那一份",
fetch.config_of(shared, {"expenseType": "travel"}).get("args"), {"dept": "{form.dept}"})
eq("带出没另挑一家时问的就是这一条那一家",
fetch.config_of(shared, {"expenseType": "travel"}).get("source"), "erp_vendors")
with_args = {"key": "vendor", "type": "picker", "optionSource": "dataSource", "dataSourceCode": "crm_bank",
"optionRoutes": [{"source": "dataSource", "when": TRAVEL, "dataSourceCode": "erp_bank",
"dataSourceArgs": {"code": "{form.vendor}"},
"fill": {"args": {"code": "{form.other}"}, "picks": {"bank": "bankName"}}}]}
eq("带出自己写了入参就以它为准",
fetch.config_of(with_args, {"expenseType": "travel"}).get("args"), {"code": "{form.other}"})
miss = fetch.config_of(field, {"expenseType": "meet", "vendor": "V1"})
ok("一条都不成立回落到字段那一份", miss is None, miss)
# 命中的那一条没自带带出 → 也是回落(老表单正是这个样子)
plain = {"key": "vendor", "type": "picker", "optionSource": "dataSource", "dataSourceCode": "crm_bank",
"optionRoutes": [{"source": "dataSource", "when": TRAVEL, "dataSourceCode": "erp_bank"}]}
eq("命中的那条没带出就回落", fetch.config_of(plain, {"expenseType": "travel"}), None)
# 带出另挑一家:候选问 A 家清单、那几列在 B 家
other = {"key": "vendor", "type": "picker", "optionSource": "dataSource", "dataSourceCode": "crm_bank",
"optionRoutes": [{"source": "dataSource", "when": TRAVEL, "dataSourceCode": "erp_bank",
"fill": {"source": "crm_bank", "picks": {"bank": "bankName"}}}]}
eq("带出可以另问一家", fetch.config_of(other, {"expenseType": "travel"}).get("source"), "crm_bank")
# 还没选源的条目:没有可带出的列
empty = {"key": "vendor", "type": "picker", "optionSource": "dataSource",
"optionRoutes": [{"source": "dataSource", "when": TRAVEL, "fill": {"picks": {"a": "b"}}}]}
eq("那一条还没选源就不带出", fetch.config_of(empty, {"expenseType": "travel"}), None)
eq("这一格会不会往外写值", fetch.has_fetch(field), True)
eq("只配了候选路由也算配过取数",
fetch.has_fetch({"key": "v", "type": "picker",
"optionRoutes": [{"source": "dataSource", "dataSourceCode": "erp",
"fill": {"picks": {"bank": "b"}}}]}), True)
eq("什么都没配", fetch.has_fetch({"key": "v", "type": "text"}), False)
# ---------------------------------------------------------------------------
# 2. 运行时:带出写进目标格,这一格自己那一个值不动
# ---------------------------------------------------------------------------
def check_runtime(db: Session) -> None:
SENT.clear()
data = apply(db, routed(), {"expenseType": "travel", "vendor": "V1", "dept": "制造事业部", "bankName": "", "creditLimit": ""})
eq("带出写进了开户行那一格", data["bankName"], "中国银行总行")
eq("额度那一格也带上了", data["creditLimit"], "50000")
eq("这一格自己那一个值没被盖掉", data["vendor"], "V1")
eq("问的就是命中的那一家,带的是刚选中的那个供应商", SENT, [{"source": "erp_bank", "code": "V1"}])
trace = (data.get(fetch.TRACE_KEY) or {}).get("vendor") or {}
eq("留痕照记这一笔外呼", trace.get("source"), "erp_bank")
# 带出去向里指着自己那一格的老配置(设计期已拦,这里兜接口直传那一条路)
SENT.clear()
selfish = routed()
selfish[0]["optionRoutes"][0]["fill"]["picks"]["value"] = "vendor"
data = apply(db, selfish, {"expenseType": "travel", "vendor": "V1", "dept": "制造事业部",
"bankName": "", "creditLimit": ""})
eq("带出去向里指着自己的那一行不写", data["vendor"], "V1")
eq("该写的格子照写", data["bankName"], "中国银行总行")
# 换一家:带出去向跟着换,问的是另一家
SENT.clear()
data = apply(db, routed(), {"expenseType": "meet", "vendor": "V2", "bankName": "", "creditLimit": ""})
eq("回落那条路这一版没配字段级取数,一个请求都不发", SENT, [])
eq("没跑就不动任何格子", data["bankName"], "")
# ---------------------------------------------------------------------------
# 3. 回落:字段那份 fetch 仍然照跑
# ---------------------------------------------------------------------------
def check_fallback(db: Session) -> None:
SENT.clear()
rows = routed(own=True)
data = apply(db, rows, {"expenseType": "meet", "vendor": "V2", "bankName": ""})
eq("一条都不成立时跑字段上那份取数", [item["source"] for item in SENT], ["crm_bank"])
eq("字段那份的带出照写", data["bankName"], "招商银行分行")
SENT.clear()
data = apply(db, routed(own=True),
{"expenseType": "travel", "vendor": "V1", "bankName": ""})
eq("命中那条自带带出时只跑它那一份", [item["source"] for item in SENT], ["erp_bank"])
eq("带出写的是命中那一条的去向", data["bankName"], "中国银行总行")
eq("这一格那一个值还是人挑的", data["vendor"], "V1")
# ---------------------------------------------------------------------------
# 4. 失败策略:不盖这一格,也不清零它
# ---------------------------------------------------------------------------
def check_on_error(db: Session) -> None:
from app.engine import engine as engine_module
rows = routed(own=True, on_error="block")
# onError 在合成时从字段那份继承(它问的是「这一格怎么待人」)
SENT.clear()
try:
apply(db, rows, {"expenseType": "travel", "vendor": "V404", "bankName": ""})
eq("取不到时 block 该挡提交", "没挡", "挡了")
except engine_module.EngineError as exc:
ok("取不到时 block 挡提交,报错说的是这一条的带出", "外部数据取不到" in str(exc), str(exc))
# zero 也不该去清这一格:要清的本来不是它
rows[0]["fetch"]["onError"] = "zero"
data = apply(db, rows, {"expenseType": "travel", "vendor": "V404", "bankName": "", "creditLimit": ""})
eq("zero 那档不清这一格自己那一个值", data["vendor"], "V404")
eq("zero 那档也不清带出去向那两格", (data["bankName"], data["creditLimit"]), ("", ""))
# ---------------------------------------------------------------------------
# 5. 设计期体检
# ---------------------------------------------------------------------------
def check_design_time(db: Session) -> None:
keys = KEYS
good = routed()[0]
eq("配好的那份不报错", formruntime.option_source_problems(good, db, keys), [])
dead = routed()[0]
dead["optionRoutes"][0]["fill"] = {"source": "erp_bank", "picks": {"bank": "gone_field"}}
problems = formruntime.option_source_problems(dead, db, keys)
ok("带出去向那一格已经被删掉要说", any("gone_field" in text for text in problems), problems)
ok("门牌写「第 N 条候选来源的带出」", any("第 1 条候选来源的带出" in text for text in problems), problems)
undeclared = routed()[0]
undeclared["optionRoutes"][0]["fill"] = {"source": "erp_bank", "picks": {"nope": "bankName"}}
problems = formruntime.option_source_problems(undeclared, db, keys)
ok("带出的键不在源声明的清单里要说", any("nope" in text for text in problems), problems)
ref = routed()[0]
ref["optionRoutes"][0]["fill"] = {"source": "erp_bank", "args": {"code": "{form.gone}"},
"picks": {"bank": "bankName"}}
problems = formruntime.option_source_problems(ref, db, keys)
ok("入参引用掉在地上要说", any("gone" in text for text in problems), problems)
# 带出去向不能是这一格自己(这一格的值是人挑的)
self_ref = routed()[0]
self_ref["optionRoutes"][0]["fill"] = {"source": "erp_bank", "picks": {"bank": "vendor"}}
problems = formruntime.option_source_problems(self_ref, db, keys)
ok("带进自己那一格要说", any("自己" in text for text in problems), problems)
# ---------------------------------------------------------------------------
# 6. 保存那一刻的清洗
# ---------------------------------------------------------------------------
def check_cleaning() -> None:
field = {"key": "vendor", "type": "picker", "optionSource": "dataSource", "dataSourceCode": "crm_bank",
"optionRoutes": [
{"source": "dataSource", "dataSourceCode": "erp_bank",
"fill": {"source": "", "args": {"code": "{form.x} ", " ": "y", "k": ""},
"picks": {"bank": " bankName "}, "extras": {"": "data.a", "b": " data.b "},
"note": "带出不该有备注那一格"}},
{"source": "dict", "dictCode": "d", "fill": {"picks": {"a": "b"}}},
]}
cleaned = dicts.clean_routes(field)
eq("清洗只留说得出的那几格", cleaned[0]["fill"],
{"args": {"code": "{form.x}"}, "picks": {"bank": "bankName"}, "extras": {"b": "data.b"}})
eq("空 source 不留", "source" in cleaned[0]["fill"], False)
eq("字典那一条的带出当残骸丢掉", "fill" in cleaned[1], False)
eq("整块都没填时不留空壳", dicts.clean_routes(
{"key": "v", "type": "picker", "optionRoutes": [{"source": "dataSource", "dataSourceCode": "e",
"fill": {"picks": {"": ""}}}]})[0].get("fill"), None)
eq("洗一遍是幂等的", dicts.clean_routes({"key": "v", "type": "picker", "optionRoutes": cleaned}), cleaned)
# ---------------------------------------------------------------------------
# 7. 前后端对齐:键名一份、常量一份
# ---------------------------------------------------------------------------
def check_parity() -> None:
root = pathlib.Path(__file__).resolve().parents[2]
ts = root / "frontend/src/utils/optionSource.ts"
if not ts.exists():
print("[跳过] 找不到前端那份 " + str(ts))
return
text = ts.read_text(encoding="utf-8")
ok("带出那个键名两边同一个", f"export const ROUTE_FILL_KEY = '{dicts.ROUTE_FILL_KEY}'" in text, True)
for table in dicts.ROUTE_FILL_TABLES:
ok(f"三张表里的「{table}」两边都在", f"'{table}'" in text, table)
ok("前端也认「只写带出去向」这一记号",
"fillOnly" in (root / "frontend/src/types/index.ts").read_text(encoding="utf-8"), True)
fetch_ts = (root / "frontend/src/utils/formFetch.ts").read_text(encoding="utf-8")
ok("前端那份也按此刻命中的那条合成", "routeFetchConfig" in fetch_ts and "fetchConfigOf" in fetch_ts, True)
ok("前端也只写带出去向、不盖这一格", "fetchPickWrites" in fetch_ts, True)
# 后端这份不该把这一格的值写回去
body = fetch.__doc__ or ""
ok("后端那份的说明里钉着同一句话", "fillOnly" in pathlib.Path(fetch.__file__).read_text(encoding="utf-8"), body[:60])
def main(argv: list[str]) -> int:
db = new_session()
fetch._cache.clear()
# 这一趟不碰 Redis:带出的那份缓存与留痕不该依赖共享缓存活着
shared_cache.get_json = lambda *a, **k: None # type: ignore[assignment]
shared_cache.set_json = lambda *a, **k: None # type: ignore[assignment]
fetch.http_request = fake_http # type: ignore[assignment]
seed(db)
stages = [
("命中哪一条就按那一条带出", check_compose),
("带出写进目标格、这一格不动", lambda: check_runtime(db)),
("一条都不成立回落到字段那份", lambda: check_fallback(db)),
("取不到时不盖也不清这一格", lambda: check_on_error(db)),
("设计期逐条体检", lambda: check_design_time(db)),
("保存那一刻的清洗", check_cleaning),
("前后端键名与常量对齐", check_parity),
]
for title, stage in stages:
before = len(FAILS)
try:
stage()
except Exception as exc: # noqa: BLE001 某一段炸了也要跑完剩下的
FAILS.append(f"{title} 这一段抛异常:{exc!r}")
print(f"[FAIL] {title} 抛异常:{exc!r}")
marks = "通过" if len(FAILS) == before else f"{len(FAILS) - before} 条不对"
print(f"[{marks}] {title}")
for line in FAILS:
print(f"[FAIL] {line}")
if FAILS:
print(f"共 {len(FAILS)} 条不对")
return 1
print(f"通过:候选路由自带的带出与前端口径一致({PASSED} 项)")
return 0
if __name__ == "__main__":
raise SystemExit(main(sys.argv[1:]))