202 lines
11 KiB
Python
202 lines
11 KiB
Python
#!/usr/bin/env python3
|
||
"""守字典项批量导入(``service/dicts.import_items``):一次贴一批进来,逐条结论必须说得住。
|
||
|
||
字典页原先只有一格一格「加字典项」,建完字典要十几二十个选项就得点十几二十次,
|
||
所以补了导入。这一层最容易坏的三件事都不在"能不能写进去"上,而在**结论对不对**:
|
||
|
||
1. **一行一个结论**。坏行单独报出来、其余照落;既不能为一格写歪的 JSON 回滚整批,
|
||
也不能把没收的行悄悄丢了让人以为都进去了。
|
||
2. **导入不等于全量**。同步那份是"上游给的就是全部",没出现的项要停用;
|
||
导入只是"再补一批",没出现的项必须原样留着——只贴三行就把手工字典清空,
|
||
是能把所有人的下拉打回空白的那种事故。
|
||
3. **顺序不能被导入打乱**。没给排序就接在现有最大序号后面;给了排序才动它。
|
||
|
||
顺带钉住这几条容易漂的口径:本批内重复值只留第一条、超长是挡下来说原因而不是
|
||
偷偷截断、``orderNumber`` 与 ``order_number`` 两种写法都认、"停用/0/false" 都算停用、
|
||
覆盖模式下什么都没变算跳过(别报成"改了它")、导完读得到的就是刚导进去的那份。
|
||
|
||
库里跑真行再自己删干净,只碰自己那本字典。跑在 backend 目录下::
|
||
|
||
PYTHONPATH=. python3 scripts/check_dict_import.py
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import pathlib
|
||
import sys
|
||
|
||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent))
|
||
|
||
from sqlalchemy import select
|
||
|
||
from app import models
|
||
from app.db import SessionLocal
|
||
from app.envelope import ApiError
|
||
from app.service import dicts
|
||
|
||
FAILS: list[str] = []
|
||
PASSED = 0
|
||
CODE = "zz-check-dict-import"
|
||
|
||
|
||
def check(label: str, ok: bool, detail: str = "") -> bool:
|
||
global PASSED
|
||
if ok:
|
||
PASSED += 1
|
||
print(f" \033[32m✓\033[0m {label}")
|
||
else:
|
||
FAILS.append(label)
|
||
print(f" \033[31m✗\033[0m {label}{(' << ' + detail) if detail else ''}")
|
||
return ok
|
||
|
||
|
||
def purge(db) -> None:
|
||
"""把这本体检字典的项与分类都删干净(上一次跑挂了留下的也算)。"""
|
||
for item in db.execute(select(models.DictItem).where(models.DictItem.type == CODE)).scalars().all():
|
||
db.delete(item)
|
||
row = db.execute(select(models.DictType).where(models.DictType.code == CODE)).scalar_one_or_none()
|
||
if row is not None:
|
||
db.delete(row)
|
||
db.commit()
|
||
dicts.invalidate(CODE)
|
||
|
||
|
||
def values(db) -> list[str]:
|
||
return [str(item.value) for item in dicts.item_rows(db, CODE)]
|
||
|
||
|
||
def of(db, value: str) -> models.DictItem:
|
||
return db.execute(
|
||
select(models.DictItem).where(models.DictItem.type == CODE, models.DictItem.value == value)
|
||
).scalar_one()
|
||
|
||
|
||
def main() -> int:
|
||
db = SessionLocal()
|
||
try:
|
||
purge(db)
|
||
db.add(models.DictType(code=CODE, name="导入体检", enabled=True, tree=False,
|
||
source=models.DictType.SOURCE_MANUAL))
|
||
db.commit()
|
||
row = dicts.get_type(db, CODE)
|
||
|
||
print("\n[1] 第一次导入:一行一个结论")
|
||
result = dicts.import_items(db, row, items=[
|
||
{"value": "A1", "label": "六角螺栓", "extra": {"price": 12}},
|
||
{"value": "A2", "label": "六角螺母"},
|
||
{"value": "", "label": "没写取值"},
|
||
{"value": "A3", "label": "垫片", "extra": "price=3;unit=个"},
|
||
{"value": "A1", "label": "本批里重复的一行"},
|
||
{"value": "A4", "label": "自己当自己的上级", "parent": "A4"},
|
||
{"value": "B" * 300, "label": "超长取值"},
|
||
{"value": "A11", "label": "附加值写歪的", "extra": "顺手写的一句说明"},
|
||
])
|
||
check("三行好的落库、五行坏的各有原因",
|
||
(result["created"], result["updated"], result["skipped"], len(result["rejected"])) == (3, 0, 0, 5),
|
||
str(result))
|
||
check("ok=False:有行没收就要说出来", result["ok"] is False)
|
||
check("报文把几种下场分开数清", "新增 3 项" in result["message"] and "5 行没收" in result["message"],
|
||
result["message"])
|
||
reasons = " ".join(f"{item['row']}:{item['reason']}" for item in result["rejected"])
|
||
check("空值那行说的是没填写值", "3:" in reasons and "没填写值" in reasons, reasons)
|
||
check("附加值既不是 JSON 也写不成键值对的那行,报怎么写",
|
||
"8:" in reasons and "附加值" in reasons, reasons)
|
||
check("本批重复的那行指出跟第几行重复", "5:" in reasons and "第 1 行" in reasons, reasons)
|
||
check("上级是自己的那行挡下来", "6:" in reasons and "上级" in reasons, reasons)
|
||
check("超长取值挡下来说原因,而不是截一半存进去",
|
||
"7:" in reasons and "超过" in reasons and "B" * 300 not in values(db), reasons)
|
||
check("库里就是落进去的三项", values(db) == ["A1", "A2", "A3"], str(values(db)))
|
||
check("附加值 JSON 真的落了库", of(db, "A1").extra == {"price": 12}, str(of(db, "A1").extra))
|
||
check("附加值写成 price=3;unit=个 这样的键值对也认(表格里敲 JSON 太别扭)",
|
||
of(db, "A3").extra == {"price": "3", "unit": "个"}, str(of(db, "A3").extra))
|
||
check("没给排序就接在现有后面(1、2、3 顺着排)",
|
||
[of(db, v).order_number for v in ("A1", "A2", "A3")] == [1, 2, 3],
|
||
str([of(db, v).order_number for v in ("A1", "A2", "A3")]))
|
||
check("没写显示名的那行拿取值顶上", of(db, "A2").label == "六角螺母", of(db, "A2").label)
|
||
|
||
print("\n[2] 再导一批:skip 模式不动已有的")
|
||
before = (of(db, "A1").label, of(db, "A1").order_number, of(db, "A1").enabled)
|
||
result = dicts.import_items(db, row, items=[
|
||
{"value": "A1", "label": "改了名字"},
|
||
{"value": "A5", "label": "弹簧垫圈", "orderNumber": 100},
|
||
{"value": "A6", "label": "被停用的", "enabled": "停用"},
|
||
{"value": "A7", "label": "写不明白的启用列", "enabled": "大概吧"},
|
||
])
|
||
check("已存在的那条算跳过,新的一算新增",
|
||
(result["created"], result["updated"], result["skipped"], len(result["rejected"])) == (3, 0, 1, 0),
|
||
str(result))
|
||
check("skip 模式真的没碰已有项",
|
||
(of(db, "A1").label, of(db, "A1").order_number, of(db, "A1").enabled) == before, str(before))
|
||
check("给了排序就用给的", of(db, "A5").order_number == 100, str(of(db, "A5").order_number))
|
||
check("没给排序的接在已有最大之后(不受给过 100 的那条影响)",
|
||
[of(db, v).order_number for v in ("A6", "A7")] == [4, 5],
|
||
str([of(db, v).order_number for v in ("A6", "A7")]))
|
||
check("「停用」两个字算停用", of(db, "A6").enabled is False)
|
||
check("看不明白的启用列按默认(启用),不猜成停用", of(db, "A7").enabled is True)
|
||
check("下划线写法也认(order_number 与 orderNumber 同一条路)",
|
||
dicts.import_items(db, row, items=[
|
||
{"value": "A8", "order_number": "7"},
|
||
{"value": "A8b", "order_number": "第一个"},
|
||
])["created"] == 2)
|
||
check("排序给了数字就用数字", of(db, "A8").order_number == 7, str(of(db, "A8").order_number))
|
||
check("排序写成文字就当没给:接在现有最大后面,不为它报错",
|
||
of(db, "A8b").order_number > 100, str(of(db, "A8b").order_number))
|
||
|
||
print("\n[3] overwrite 模式:改到的才算覆盖")
|
||
result = dicts.import_items(db, row, mode="overwrite", items=[
|
||
{"value": "A1", "label": "六角螺栓(改名)", "extra": {"price": 15}, "orderNumber": 50},
|
||
{"value": "A2", "label": "六角螺母"},
|
||
])
|
||
check("改了的算覆盖、一模一样那行算跳过",
|
||
(result["created"], result["updated"], result["skipped"]) == (0, 1, 1), str(result))
|
||
check("覆盖改了名字与附加值",
|
||
of(db, "A1").label == "六角螺栓(改名)" and of(db, "A1").extra == {"price": 15},
|
||
f"{of(db, 'A1').label} {of(db, 'A1').extra}")
|
||
check("给了排序才动顺序", of(db, "A1").order_number == 50, str(of(db, "A1").order_number))
|
||
check("没给排序的沿用原来的顺序", of(db, "A2").order_number == 2, str(of(db, "A2").order_number))
|
||
check("覆盖完读得到的就是刚导进去的那份(缓存当场作废)",
|
||
any(str(item["label"]) == "六角螺栓(改名)" for item in dicts.items_of(db, CODE)))
|
||
|
||
print("\n[4] 导入不是全量:没出现的项原样留着")
|
||
dicts.import_items(db, row, items=[{"value": "A9", "label": "只有这一条"}])
|
||
check("之前那些项一项都没被停用或删掉",
|
||
len(values(db)) == 9 and all(of(db, v).enabled for v in ("A5", "A7", "A9")), str(values(db)))
|
||
dicts.import_items(db, row, items=[
|
||
{"value": "A10", "extra": "url=https://x.io?a=1;备注=先填;不合格退回"},
|
||
])
|
||
check("值里的 = 与全角分号都不当分隔符切坏",
|
||
of(db, "A10").extra == {"url": "https://x.io?a=1", "备注": "先填;不合格退回"},
|
||
str(of(db, "A10").extra))
|
||
|
||
print("\n[5] 整批层面的挡法")
|
||
for label, kwargs in (
|
||
("空批不写库", {"items": []}),
|
||
("超过上限报一句", {"items": [{"value": f"X{i}"} for i in range(dicts.MAX_IMPORT_ITEMS + 1)]}),
|
||
):
|
||
try:
|
||
dicts.import_items(db, row, **kwargs)
|
||
ok, detail = False, "没报错"
|
||
except ApiError as exc:
|
||
ok = exc.status_code == 400 and bool(exc.detail)
|
||
detail = f"{exc.status_code} {exc.detail}"
|
||
check(label, ok, detail)
|
||
check("上限那一行也没落进去", "X0" not in values(db), str(values(db)))
|
||
result = dicts.import_items(db, row, items=[{"row": 77, "label": "只有显示名"}])
|
||
check("行号认前端带来的那一格:界面贴的第几行就报第几行",
|
||
[item["row"] for item in result["rejected"]] == [77], str(result["rejected"]))
|
||
check("导入认的列长与模型一致(改了模型记得回来看这条)",
|
||
dicts.IMPORT_FIELD_MAX == models.DictItem.__table__.c.value.type.length,
|
||
str(models.DictItem.__table__.c.value.type.length))
|
||
|
||
print(f"\n合计 {PASSED + len(FAILS)} 项:通过 {PASSED} / 失败 {len(FAILS)}")
|
||
return 1 if FAILS else 0
|
||
finally:
|
||
try:
|
||
purge(db)
|
||
finally:
|
||
db.close()
|
||
|
||
|
||
if __name__ == "__main__":
|
||
raise SystemExit(main())
|