fourcal-pms/backend/tests/test_dict.py

301 lines
14 KiB
Python
Raw Permalink 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.

"""数据字典:代码同步、界面维护、护栏,以及"下拉框只剩一个来源"这条回归。
这里钉的都是会静默腐化的东西:内置取值被改掉、代码和库两份名字对不上、
前端自己抄一份常量。真出事的时候没人报错,只是列表上显示的名字和下拉框不一样。
"""
from __future__ import annotations
import uuid
import pytest
from app import dicts as store
VALUE_TAGS = {"A", "B"}
@pytest.fixture(scope="module")
def ctx():
return {}
def _code(prefix: str = "cust") -> str:
"""每次跑都换一个编码:字典表是留着不清的,撞了上一次的残留会误报"编码已存在"。"""
return f"{prefix}{uuid.uuid4().hex[:8]}"
# ---------------------------------------------------------------------------
# 代码层
# ---------------------------------------------------------------------------
def test_every_code_dict_is_shipped_to_the_frontend(client, admin_headers):
"""``/bootstrap`` 必须带上全部代码字典,前端就不用再为某个下拉框单开一条接口。"""
enums = client.get("/api/v1/bootstrap", headers=admin_headers).json()["data"]["enums"]
missing = set(store.SPECS) - set(enums)
assert not missing, f"bootstrap 少了这些字典:{sorted(missing)}"
def test_project_options_and_enums_agree(client, admin_headers):
"""项目类型曾在接口和前端各写一份,名字对不上也没人报错——这条就是钉住那次。"""
enums = client.get("/api/v1/bootstrap", headers=admin_headers).json()["data"]["enums"]
options = client.get("/api/v1/projects/options", headers=admin_headers).json()["data"]
assert options["types"] == enums["projectType"]
assert options["stages"] == enums["projectStage"]
assert options["underwrittenModes"] == enums["underwrittenMode"]
assert options["memberRoles"] == enums["projectMemberRole"]
def test_dict_values_match_what_the_calc_engine_reads():
"""下拉框给的编码,必须是计算内核真认的那些。
老毛病:前端自己抄一份产品归属(integration/other),内核的映射表里根本没这两个键,
于是那几笔采购额静默投影不到 project 的产品金额列上。费用归属同理多出一个
finance_cost——选它的人等于白填一行。
"""
from app.models import OtherCostBucket, ProductCategory
from app.service.calc import mapping
assert set(ProductCategory.LABELS) == set(mapping.PRODUCT_CATEGORY_TO_FIELD)
# engine.estimate_payload 按这四个 bucket 取数,多一个少一个都算漏了一层
assert set(OtherCostBucket.LABELS) == {
"project_manage", "other_cost", "capital_interest", "company_manage"}
# 两边都得已经同步进字典,前端才没有第二份可抄
assert {row["value"] for row in store.SPECS["productCategory"].options()} == set(ProductCategory.LABELS)
assert {row["value"] for row in store.SPECS["otherCostBucket"].options()} == set(OtherCostBucket.LABELS)
def test_sync_is_idempotent():
"""重启不能把界面上改过的名字冲回去,也不能长出第二份同样的取值。"""
from sqlalchemy import func, select
from app.db import SessionFactory
from app.models import DictItem, DictType
with SessionFactory()() as db:
store.sync(db)
store.sync(db)
db.commit()
types = db.execute(select(func.count()).select_from(DictType)
.where(DictType.is_deleted.is_(False))).scalar()
dup = db.execute(select(func.count()).select_from(
select(DictItem.dict_type_id, DictItem.value)
.where(DictItem.is_deleted.is_(False))
.group_by(DictItem.dict_type_id, DictItem.value)
.having(func.count() > 1).subquery())).scalar()
assert types >= len(store.SPECS)
assert dup == 0, "同一份字典里出现了重复取值"
def test_sync_does_not_overwrite_edited_labels():
"""改过名字的内置字典,重启后还得是改过的名字(要回到代码值请用「恢复默认」)。"""
from sqlalchemy import select
from app.db import SessionFactory
from app.models import DictItem, DictType
with SessionFactory()() as db:
row = db.execute(select(DictItem).join(DictType, DictType.id == DictItem.dict_type_id)
.where(DictType.code == "projectType", DictItem.value == "1")
).scalars().first()
assert row is not None
original = row.label
row.label = "工程集成类(临时改名)"
db.commit()
store.sync(db)
db.commit()
again = db.get(DictItem, row.id)
assert again.label == "工程集成类(临时改名)"
again.label = original
db.commit()
store.invalidate()
# ---------------------------------------------------------------------------
# 维护页:自定义字典
# ---------------------------------------------------------------------------
def test_custom_dict_end_to_end(client, admin_headers, ctx):
code = _code("grade")
created = client.post("/api/v1/system/dicts", headers=admin_headers, json={
"code": code, "name": "客户等级", "group": "测试", "valueType": "string",
"remark": "用例自建"})
assert created.status_code == 200, created.text
type_id = created.json()["data"]["id"]
ctx.update(code=code, type_id=type_id)
for index, (value, label) in enumerate((("vip", "战略客户"), ("normal", "普通客户"))):
resp = client.post(f"/api/v1/system/dicts/{code}/items", headers=admin_headers, json={
"value": value, "label": label, "sort": (index + 1) * 10})
assert resp.status_code == 200, resp.text
data = client.get("/api/v1/dicts", headers=admin_headers, params={"types": code}).json()["data"]
assert [item["value"] for item in data[code]] == ["vip", "normal"]
assert data[code][0]["label"] == "战略客户"
# 停用一条:下拉框里没有它,但历史数据上的值照样显示得出名字
items = client.get(f"/api/v1/system/dicts/{code}/items", headers=admin_headers).json()["data"]["items"]
vip = next(row for row in items if row["value"] == "vip")
assert client.post(f"/api/v1/system/dicts/items/{vip['id']}/toggle",
headers=admin_headers).json()["data"]["enabled"] is False
data = client.get("/api/v1/dicts", headers=admin_headers, params={"types": code}).json()["data"]
assert [item["value"] for item in data[code]] == ["normal"]
from app.db import session_scope
with session_scope() as db:
assert store.label(db, code, "vip", "兜底") == "战略客户", "停用的取值也该查得到名字"
# 整类停用:下拉框给空列表,而不是报找不到
assert client.put(f"/api/v1/system/dicts/{type_id}", headers=admin_headers, json={
"code": code, "name": "客户等级", "group": "测试", "valueType": "string",
"enabled": False}).status_code == 200
data = client.get("/api/v1/dicts", headers=admin_headers, params={"types": code}).json()["data"]
assert data[code] == []
def test_custom_dict_is_visible_in_bootstrap(client, admin_headers, ctx):
"""自建字典不用改一行代码就能进 bootstrap——这是加这个模块的全部理由。"""
type_id = ctx["type_id"]
client.put(f"/api/v1/system/dicts/{type_id}", headers=admin_headers, json={
"code": ctx["code"], "name": "客户等级", "group": "测试", "valueType": "string",
"enabled": True})
enums = client.get("/api/v1/bootstrap", headers=admin_headers).json()["data"]["enums"]
assert enums[ctx["code"]] == [{"value": "normal", "label": "普通客户"}]
def test_custom_dict_cleanup(client, admin_headers, ctx):
assert client.delete(f"/api/v1/system/dicts/{ctx['type_id']}",
headers=admin_headers).json()["data"]["deleted"] is True
data = client.get("/api/v1/dicts", headers=admin_headers,
params={"types": ctx["code"]}).json()["data"]
assert data == {}
# ---------------------------------------------------------------------------
# 护栏
# ---------------------------------------------------------------------------
@pytest.mark.parametrize("payload, code", [
({"code": "Customer_Level", "name": "x", "valueType": "string"}, "invalid_code"),
({"code": "projectStage", "name": "x", "valueType": "string"}, "reserved_code"),
])
def test_type_code_is_guarded(client, admin_headers, payload, code):
resp = client.post("/api/v1/system/dicts", headers=admin_headers, json=payload)
assert resp.json()["error"]["code"] == code, resp.text
def test_reserved_code_case_insensitive_check(client, admin_headers):
"""和内置字典撞编码要挡下来,但换个编码就该建得成(顺带清掉)。"""
code = _code("stage")
assert client.post("/api/v1/system/dicts", headers=admin_headers, json={
"code": code, "name": "临时阶段字典", "valueType": "int"}).status_code == 200
row = client.get("/api/v1/system/dicts", headers=admin_headers).json()["data"]
created = next(item for item in row if item["code"] == code)
assert client.delete(f"/api/v1/system/dicts/{created['id']}",
headers=admin_headers).status_code == 200
def test_builtin_values_are_immutable(client, admin_headers):
"""内置取值是代码分支的依据:改 value、删条目都挡下来,改名字放行。"""
items = client.get("/api/v1/system/dicts/projectStage/items",
headers=admin_headers).json()["data"]["items"]
row = items[0]
body = {"value": "999", "label": row["label"], "sort": row["sort"],
"enabled": True, "tag": "", "remark": ""}
resp = client.put(f"/api/v1/system/dicts/items/{row['id']}", headers=admin_headers, json=body)
assert resp.json()["error"]["code"] == "builtin_item", resp.text
resp = client.delete(f"/api/v1/system/dicts/items/{row['id']}", headers=admin_headers)
assert resp.json()["error"]["code"] == "builtin_item", resp.text
body["value"] = row["value"]
body["label"] = row["label"]
assert client.put(f"/api/v1/system/dicts/items/{row['id']}",
headers=admin_headers, json=body).status_code == 200
stage_type = next(item for item in client.get("/api/v1/system/dicts", headers=admin_headers
).json()["data"]
if item["code"] == "projectStage")
resp = client.delete(f"/api/v1/system/dicts/{stage_type['id']}", headers=admin_headers)
assert resp.json()["error"]["code"] == "builtin_type", resp.text
def test_rename_then_reset(client, admin_headers):
"""改名能立刻生效,「恢复默认」能回到代码里的名字。"""
items = client.get("/api/v1/system/dicts/underwrittenMode/items",
headers=admin_headers).json()["data"]["items"]
row = items[0]
original = store.SPECS["underwrittenMode"].items[0][1]
body = {"value": str(row["value"]), "label": "A类-不垫资(改名)", "sort": row["sort"],
"enabled": True, "tag": "", "remark": ""}
assert client.put(f"/api/v1/system/dicts/items/{row['id']}",
headers=admin_headers, json=body).status_code == 200
enums = client.get("/api/v1/bootstrap", headers=admin_headers).json()["data"]["enums"]
assert enums["underwrittenMode"][0]["label"] == "A类-不垫资(改名)"
assert client.post("/api/v1/system/dicts/underwrittenMode/reset",
headers=admin_headers).status_code == 200
enums = client.get("/api/v1/bootstrap", headers=admin_headers).json()["data"]["enums"]
assert enums["underwrittenMode"][0]["label"] == original
def test_reset_only_works_on_code_dicts(client, admin_headers):
code = _code("noc")
client.post("/api/v1/system/dicts", headers=admin_headers, json={
"code": code, "name": "没有代码默认值", "valueType": "string"})
row = next(item for item in client.get("/api/v1/system/dicts",
headers=admin_headers).json()["data"]
if item["code"] == code)
resp = client.post(f"/api/v1/system/dicts/{code}/reset", headers=admin_headers)
assert resp.json()["error"]["code"] == "not_builtin", resp.text
client.delete(f"/api/v1/system/dicts/{row['id']}", headers=admin_headers)
def test_int_dict_rejects_non_numeric_value(client, admin_headers):
code = _code("num")
client.post("/api/v1/system/dicts", headers=admin_headers, json={
"code": code, "name": "整数型字典", "valueType": "int"})
row = next(item for item in client.get("/api/v1/system/dicts",
headers=admin_headers).json()["data"]
if item["code"] == code)
resp = client.post(f"/api/v1/system/dicts/{code}/items", headers=admin_headers, json={
"value": "不是数字", "label": "任何名字", "sort": 10})
assert resp.json()["error"]["code"] == "invalid_value", resp.text
assert client.post(f"/api/v1/system/dicts/{code}/items", headers=admin_headers, json={
"value": " 7 ", "label": "七", "sort": 10}).status_code == 200
data = client.get("/api/v1/dicts", headers=admin_headers, params={"types": code}).json()["data"]
assert data[code] == [{"value": 7, "label": "七"}], "整数型字典要按数字下发"
dup = client.post(f"/api/v1/system/dicts/{code}/items", headers=admin_headers, json={
"value": "7", "label": "重复", "sort": 20})
assert dup.json()["error"]["code"] == "duplicated_value", dup.text
client.delete(f"/api/v1/system/dicts/{row['id']}", headers=admin_headers)
def test_edit_needs_the_permission(client, admin_headers):
"""改字典是系统管理动作,只有超管那条权限码能改。"""
from app.config import settings
from tests.test_api_flow import login
# 演示账号与内置超管同一个口令,见 README「快速开始」
password = settings.seed.admin_password or "Admin@12345"
try:
headers = login(client, "wangwu", password)
except AssertionError:
pytest.skip("演示账号 wangwu 不在:[seed] demo_data = false 时没有演示账号")
if any("system:dict:edit" in code for code in
client.get("/api/v1/bootstrap", headers=headers).json()["data"]["permissions"]):
pytest.skip("wangwu 被授了 system:dict:edit,这条越权用例没法验")
resp = client.post("/api/v1/system/dicts", headers=headers, json={
"code": _code("nope"), "name": "不该建成", "valueType": "string"})
assert resp.status_code == 403, resp.text
assert client.get("/api/v1/system/dicts", headers=headers).status_code == 403