fourcal-pms/backend/tests/test_api_flow.py

1285 lines
70 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.

"""主链路接口测试:建项目 -> 概算 -> 预算 -> 送审 -> 审批 -> 投影回写。
同一 module 级 fixture 串起一个随机命名的项目,避免每条断言都重造一遍数据。
用例顺序即业务顺序,pytest 默认按定义顺序执行。
"""
from __future__ import annotations
import uuid
import pytest
from app.config import settings
#: 内置超管的账号名与口令跟着配置档走:本部署把本地账号收敛成一个 localadmin,
#: 用例里再写死 admin / Admin@12345 就会一边登不进一边查代码。
ADMIN = settings.seed.admin_account or "admin"
PASSWORD = settings.seed.admin_password or "Admin@12345"
#: 用例自己造的账号要能登录:内置超管的口令是按部署配置来的,未必过得了口令强度策略
PERSON_PASSWORD = "RoleTest@2026"
def login(client, account, password=PASSWORD):
response = client.post("/api/v1/auth/login", json={"account": account, "password": password})
assert response.status_code == 200, response.text
return {"Authorization": "Bearer " + response.json()["data"]["accessToken"]}
@pytest.fixture(scope="module")
def demo_accounts(client):
"""演示账号(张三/李四/王五)与它们的登录态。
``[seed] demo_data = false`` 的机器上根本没有这三个人——那是开发者有意清掉的演示数据,
不是代码坏了,所以这类用例整组跳过并把原因说清楚,而不是报一串 401 让人去查登录逻辑。
要跑这批用例就把 ``demo_data`` 改回 true,重启一次后端再跑。
"""
wanted = ("zhangsan", "lisi", "wangwu")
missing = [name for name in wanted
if client.post("/api/v1/auth/login",
json={"account": name, "password": PASSWORD}).status_code != 200]
if missing:
pytest.skip("演示账号缺失:" + "、".join(missing)
+ "。[seed] demo_data = false 时不种演示账号;要跑这批用例把它改回 true "
"并重启一次后端。")
return {name: login(client, name) for name in wanted}
@pytest.fixture()
def org_tree(client, admin_headers):
"""组织树。演示数据清掉之后它只能靠一次统一身份全量同步回来,没有就跳过。"""
tree = client.get("/api/v1/org/units", headers=admin_headers).json()["data"]
if not tree:
pytest.skip("组织树是空的:演示数据已清掉,且本机还没跑过统一身份全量同步")
return tree
@pytest.fixture(scope="module")
def ctx():
return {}
@pytest.fixture(scope="module")
def budgeted_project(client, admin_headers, ctx):
"""走完"建项目 + 概算 + 预算录_entry_",返回项目 id;送审类用例复用。"""
suffix = uuid.uuid4().hex[:6].upper()
created = client.post("/api/v1/projects", headers=admin_headers, json={
"name": f"接口测试项目-{suffix}",
"type": 1,
"projectNo": f"IT-{suffix}",
"customer": "测试客户",
"planStart": "2026-01",
"planEnd": "2026-06",
"underwrittenMode": 3,
"advanceInterestRate": "6",
})
assert created.status_code == 200, created.text
project_id = created.json()["data"]["id"]
ctx["project_id"] = project_id
estimate_rows = [
("income", {"income_type": 1, "name": "弱电机房设备", "include_amount": "11300000", "tax_rate": "13"}),
# 走"数量 × 单价"这一支:2180000 / 1.09 = 2000000 未税,正好把
# resolve_include 的回落路径也覆盖住
("income", {"income_type": 2, "name": "综合布线施工", "qty": "2", "unit_price": "1090000", "tax_rate": "9"}),
("cost", {"purchase_type": 1, "name": "服务器采购", "include_amount": "6780000", "tax_rate": "13",
"product_category": "huazhi"}),
("cost", {"purchase_type": 2, "name": "施工分包", "include_amount": "1090000", "tax_rate": "9"}),
("other", {"bucket": "project_manage", "name": "人员差旅费", "exclude_amount": "200000", "manual": True}),
]
for path, payload in estimate_rows:
response = client.post(f"/api/v1/finance/estimate/projects/{project_id}/lines/{path}",
headers=admin_headers, json={"data": payload})
assert response.status_code == 200, response.text
budget_rows = [
("income", {"income_type": 1, "name": "弱电机房设备", "qty": "10", "unit_price": "1130000", "tax_rate": "13"}),
("purchase", {"purchase_type": 1, "name": "服务器", "include_amount": "6780000", "tax_rate": "13",
"product_category": "huazhi", "contract_party": "某供应商"}),
("manage", {"item_code": "travel", "item_name": "人员差旅费", "total": "80000",
"pay_date": "2026-02-10", "counts_to_travel_limit": True}),
("pay_plan", {"purchase_type": 1, "amount": "6780000", "pay_date": "2026-01-20", "supplier": "某供应商"}),
("income_plan", {"receive_point": "到货验收", "amount": "11300000", "receive_date": "2026-06-20"}),
]
for path, payload in budget_rows:
response = client.post(f"/api/v1/finance/budget/projects/{project_id}/lines/{path}",
headers=admin_headers, json={"data": payload})
assert response.status_code == 200, response.text
return project_id
class TestAuthAndBootstrap:
def test_me_returns_principal_and_pruned_menu_tree(self, client, admin_headers):
data = client.get("/api/v1/auth/me", headers=admin_headers).json()["data"]
assert data["user"]["account"] == ADMIN
assert data["permissions"] == ["*"], "超管的权限码应当是通配,前端据此短路"
assert {role["code"] for role in data["roles"]} == {"super_admin"}
assert {node["name"] for node in data["menus"]} >= {"工作台", "项目管理", "审批中心", "系统管理"}
assert all("children" in node for node in data["menus"]), "菜单必须是树,不是平铺"
def test_login_rejects_bad_password(self, client):
response = client.post("/api/v1/auth/login",
json={"account": ADMIN, "password": "不对的口令"})
assert response.status_code in (400, 401)
assert response.json()["ok"] is False and response.json()["error"]["traceId"]
def test_protected_route_needs_a_token(self, client):
assert client.get("/api/v1/projects").status_code == 401
assert client.get("/api/v1/projects",
headers={"Authorization": "Bearer not-a-jwt"}).status_code == 401
def test_bootstrap_carries_enums_and_lowers_without_a_token(self, client):
data = client.get("/api/v1/bootstrap").json()["data"]
assert data["user"] is None
assert {"projectStage", "purchaseType", "candidateType", "businessModule"} <= set(data["enums"])
assert data["enums"]["projectStage"][0]["label"].startswith("S0"), "枚举要带中文标签"
def test_bootstrap_inlines_permissions_when_authenticated(self, client, admin_headers):
data = client.get("/api/v1/bootstrap", headers=admin_headers).json()["data"]
assert data["user"]["account"] == ADMIN
assert data["menus"] and data["enums"]
def test_health_is_open_and_reports_database(self, client):
body = client.get("/api/health").json()
assert body["ok"] is True and body["database"]
class TestProjectCrud:
def test_create_project_lands_in_estimate_stage(self, client, admin_headers, ctx):
suffix = uuid.uuid4().hex[:6].upper()
created = client.post("/api/v1/projects", headers=admin_headers, json={
"name": f"阶段检查项目-{suffix}", "type": 1, "projectNo": f"ST-{suffix}",
"planStart": "2026-01", "planEnd": "2026-03",
})
assert created.status_code == 200, created.text
detail = client.get(f"/api/v1/projects/{created.json()['data']['id']}",
headers=admin_headers).json()["data"]
assert detail["stage"] == 0 and detail["stageLabel"] == "S0-概算立项"
def test_blank_name_is_rejected_by_validation(self, client, admin_headers):
assert client.post("/api/v1/projects", headers=admin_headers,
json={"name": ""}).status_code == 422
def test_unknown_project_is_404(self, client, admin_headers):
assert client.get("/api/v1/projects/99999999", headers=admin_headers).status_code == 404
def test_stage_can_be_advanced(self, client, admin_headers, ctx, budgeted_project):
project_id = ctx["project_id"]
moved = client.post(f"/api/v1/projects/{project_id}/stage", headers=admin_headers,
json={"stage": 2, "remark": "进入方案设计"})
assert moved.status_code == 200, moved.text
detail = client.get(f"/api/v1/projects/{project_id}", headers=admin_headers).json()["data"]
assert detail["stage"] == 2
def test_list_returns_page_meta_and_scope(self, client, admin_headers, ctx, budgeted_project):
body = client.get("/api/v1/projects", headers=admin_headers,
params={"keyword": f"IT-{ctx['project_id']}"}).json()
assert body["ok"] is True
assert set(body["data"]) >= {"items", "meta", "scope"}
assert body["data"]["scope"]["unlimited"] is True
class TestProjectDelete:
"""删除项目:软删除、回收站、恢复,以及挡在中间的审批。"""
@staticmethod
def _create(client, headers, prefix="删除测试项目"):
suffix = uuid.uuid4().hex[:6].upper()
created = client.post("/api/v1/projects", headers=headers, json={
"name": f"{prefix}-{suffix}", "type": 2, "projectNo": f"DEL-{suffix}"})
assert created.status_code == 200, created.text
return created.json()["data"]["id"], f"DEL-{suffix}"
def test_delete_check_says_a_bare_project_is_deletable(self, client, admin_headers):
project_id, _ = self._create(client, admin_headers)
body = client.get(f"/api/v1/projects/{project_id}/delete-check",
headers=admin_headers).json()
assert body["ok"] is True, body
data = body["data"]
assert data["deletable"] is True and data["blockers"] == []
# 创建人同时落成项目负责人,成员表不会空着
assert data["stats"]["members"] == 1
def test_soft_delete_hides_the_project_but_keeps_it_in_the_bin(self, client, admin_headers):
project_id, project_no = self._create(client, admin_headers)
response = client.request("DELETE", f"/api/v1/projects/{project_id}",
headers=admin_headers, json={"reason": "重复创建"})
assert response.status_code == 200, response.text
assert client.get(f"/api/v1/projects/{project_id}",
headers=admin_headers).status_code == 404
alive = client.get("/api/v1/projects", headers=admin_headers,
params={"keyword": project_no}).json()["data"]["items"]
assert alive == [], "已删除的项目不该还出现在正常列表里"
rows = client.get("/api/v1/projects", headers=admin_headers,
params={"deletedOnly": True, "keyword": project_no}
).json()["data"]["items"]
assert [row["id"] for row in rows] == [project_id]
assert rows[0]["deleteReason"] == "重复创建"
assert rows[0]["deletedByName"] and rows[0]["deletedAt"]
def test_deleted_project_shuts_the_finance_routes_too(self, client, admin_headers):
"""删除是按项目整条封的:概算/预算接口不能还能读写它的明细。"""
project_id, _ = self._create(client, admin_headers)
assert client.request("DELETE", f"/api/v1/projects/{project_id}",
headers=admin_headers).status_code == 200
assert client.get(f"/api/v1/finance/estimate/projects/{project_id}/revision",
headers=admin_headers).status_code == 404
def test_restore_brings_it_back_and_clears_the_trail(self, client, admin_headers):
project_id, project_no = self._create(client, admin_headers)
client.request("DELETE", f"/api/v1/projects/{project_id}", headers=admin_headers,
json={"reason": "误建"})
assert client.post(f"/api/v1/projects/{project_id}/restore",
headers=admin_headers).status_code == 200
detail = client.get(f"/api/v1/projects/{project_id}", headers=admin_headers).json()["data"]
assert detail["deleteReason"] == "" and detail["deletedAt"] == ""
rows = client.get("/api/v1/projects", headers=admin_headers,
params={"keyword": project_no}).json()["data"]["items"]
assert [row["id"] for row in rows] == [project_id]
def test_restoring_a_live_project_is_a_conflict(self, client, admin_headers):
project_id, _ = self._create(client, admin_headers)
assert client.post(f"/api/v1/projects/{project_id}/restore",
headers=admin_headers).status_code == 409
def test_a_running_approval_blocks_the_delete(self, client, admin_headers):
"""审批还在流转就删不掉:待办挂在别人名下,项目没了那些待办就点不开。"""
project_id, _ = self._create(client, admin_headers)
submitter = client.get("/api/v1/auth/me", headers=admin_headers).json()["data"]["user"]["id"]
from app.db import SessionFactory
from app.models import ApprovalInstance, InstanceStatus
session = SessionFactory()()
try:
instance = ApprovalInstance(
flow_id=1, flow_key="it_delete_block", flow_name="接口测试:挡删除",
business_module="estimate", project_id=project_id, project_name="挡住删除",
status=InstanceStatus.REVIEWING, submitter_id=submitter, submitter_name="接口测试",
)
session.add(instance)
session.commit()
finally:
session.close()
try:
check = client.get(f"/api/v1/projects/{project_id}/delete-check",
headers=admin_headers).json()["data"]
assert check["deletable"] is False
assert check["blockers"][0]["code"] == "approval_in_progress"
response = client.request("DELETE", f"/api/v1/projects/{project_id}",
headers=admin_headers)
assert response.status_code == 409, response.text
assert response.json()["error"]["code"] == "approval_in_progress"
finally:
session = SessionFactory()()
try:
session.query(ApprovalInstance).filter(
ApprovalInstance.id == instance.id).delete()
session.commit()
finally:
session.close()
def test_roles_without_the_code_are_refused(self, client, admin_headers, demo_accounts):
"""财务能看全公司项目,不等于能把别人的项目删掉——权限码与归属两道闸各管一件事。"""
project_id, _ = self._create(client, admin_headers)
refused = client.request("DELETE", f"/api/v1/projects/{project_id}",
headers=demo_accounts["wangwu"])
assert refused.status_code == 403, refused.text
assert "缺少权限" in refused.json()["error"]["message"]
def test_a_teammate_without_ownership_cannot_delete(self, client, admin_headers, demo_accounts):
project_id, _ = self._create(client, admin_headers)
refused = client.request("DELETE", f"/api/v1/projects/{project_id}",
headers=demo_accounts["zhangsan"])
assert refused.status_code == 403, refused.text
class TestProjectPurge:
"""彻底删除:只能销毁回收站里的项目,销毁之后业务数据一行不剩。"""
@staticmethod
def _create(client, headers):
suffix = uuid.uuid4().hex[:6].upper()
created = client.post("/api/v1/projects", headers=headers, json={
"name": f"销毁测试项目-{suffix}", "type": 2, "projectNo": f"PRG-{suffix}"})
assert created.status_code == 200, created.text
return created.json()["data"]["id"], f"PRG-{suffix}"
@staticmethod
def _residue(client, project_id):
"""项目名下还剩多少业务行。审计日志不算,它必须留下来。"""
from app.db import SessionFactory
from app.models import (Project, ProjectMember, ProjectStageLog,
ProjectVisibleRole, Revision)
with SessionFactory()() as session:
return sum([
session.query(Project).filter(Project.id == project_id).count(),
session.query(ProjectMember).filter(
ProjectMember.project_id == project_id).count(),
session.query(ProjectStageLog).filter(
ProjectStageLog.project_id == project_id).count(),
session.query(ProjectVisibleRole).filter(
ProjectVisibleRole.project_id == project_id).count(),
session.query(Revision).filter(Revision.project_id == project_id).count(),
])
def test_a_live_project_cannot_be_purged(self, client, admin_headers):
"""没进回收站就销毁不了:少一步误删的缓冲,太容易手滑。"""
project_id, no = self._create(client, admin_headers)
refused = client.request("DELETE", f"/api/v1/projects/{project_id}/purge",
headers=admin_headers, json={"confirmName": no})
assert refused.status_code == 409, refused.text
assert refused.json()["error"]["code"] == "not_in_bin"
client.request("DELETE", f"/api/v1/projects/{project_id}", headers=admin_headers)
def test_purge_needs_the_exact_confirmation(self, client, admin_headers):
project_id, no = self._create(client, admin_headers)
client.request("DELETE", f"/api/v1/projects/{project_id}", headers=admin_headers,
json={"reason": "试销毁"})
check = client.get(f"/api/v1/projects/{project_id}/purge-check",
headers=admin_headers).json()["data"]
assert check["deletable"] is True and check["confirmName"] == no
assert check["counts"]["项目成员"] == 1
wrong = client.request("DELETE", f"/api/v1/projects/{project_id}/purge",
headers=admin_headers, json={"confirmName": "手滑打错了"})
assert wrong.status_code == 409, wrong.text
assert wrong.json()["error"]["code"] == "confirm_mismatch"
assert self._residue(client, project_id) > 0, "确认词不对的时候一行都不该少"
def test_purge_destroys_every_business_row(self, client, admin_headers):
project_id, no = self._create(client, admin_headers)
client.request("DELETE", f"/api/v1/projects/{project_id}", headers=admin_headers,
json={"reason": "重复录入"})
purged = client.request("DELETE", f"/api/v1/projects/{project_id}/purge",
headers=admin_headers, json={"confirmName": no})
assert purged.status_code == 200, purged.text
body = purged.json()["data"]
assert body["purged"] is True and body["destroyed"]["项目成员"] == 1
assert client.get(f"/api/v1/projects/{project_id}", headers=admin_headers).status_code == 404
assert client.get("/api/v1/projects", headers=admin_headers,
params={"deletedOnly": True, "keyword": no}
).json()["data"]["items"] == []
assert self._residue(client, project_id) == 0
def test_approval_history_blocks_the_destruction(self, client, admin_headers):
"""审批留痕不能跟着项目一起销毁,否则审计链断在"批过但查不到"。
这里种的是**已通过**的实例:审批还在流转时连软删除都挡(见上一组用例),
那条路已有用例守着;销毁要挡的是"历史",所以得用完结的实例来试。
"""
project_id, no = self._create(client, admin_headers)
submitter = client.get("/api/v1/auth/me", headers=admin_headers).json()["data"]["user"]["id"]
from app.db import SessionFactory
from app.models import ApprovalInstance, InstanceStatus
session = SessionFactory()()
try:
instance = ApprovalInstance(
flow_id=1, flow_key="it_purge_block", flow_name="接口测试:挡销毁",
business_module="budget", project_id=project_id, project_name="挡住销毁",
status=InstanceStatus.APPROVED, submitter_id=submitter, submitter_name="接口测试",
)
session.add(instance)
session.commit()
finally:
session.close()
try:
deleted = client.request("DELETE", f"/api/v1/projects/{project_id}", headers=admin_headers)
assert deleted.status_code == 200, deleted.text
check = client.get(f"/api/v1/projects/{project_id}/purge-check",
headers=admin_headers).json()["data"]
assert check["deletable"] is False
assert check["blockers"][0]["code"] == "has_approval_history"
refused = client.request("DELETE", f"/api/v1/projects/{project_id}/purge",
headers=admin_headers, json={"confirmName": no})
assert refused.status_code == 409, refused.text
assert refused.json()["error"]["code"] == "has_approval_history"
assert self._residue(client, project_id) > 0
finally:
session = SessionFactory()()
try:
session.query(ApprovalInstance).filter(
ApprovalInstance.id == instance.id).delete()
session.commit()
finally:
session.close()
client.post(f"/api/v1/projects/{project_id}/restore", headers=admin_headers)
def test_a_teammate_without_the_purge_code_is_refused(self, client, admin_headers, demo_accounts):
"""删除能恢复、销毁不能,所以销毁是另一个权限码:财务连删除都没有,更没有销毁。"""
project_id, no = self._create(client, admin_headers)
refused = client.request("DELETE", f"/api/v1/projects/{project_id}/purge",
headers=demo_accounts["wangwu"], json={"confirmName": no})
assert refused.status_code == 403, refused.text
assert "project:project:purge" in refused.json()["error"]["message"]
class TestAuditTrail:
"""写操作审计:所有改数据的请求都要留下一条能查回来的账。"""
@staticmethod
def _logs(client, headers, **params):
body = client.get("/api/v1/system/operation-logs", headers=headers,
params=params).json()
assert body["ok"] is True, body
return body["data"]
def test_writes_are_logged_with_who_what_and_result(self, client, admin_headers):
suffix = uuid.uuid4().hex[:6].upper()
created = client.post("/api/v1/projects", headers=admin_headers, json={
"name": f"审计用例-{suffix}", "type": 1, "projectNo": f"AUD-{suffix}"})
project_id = created.json()["data"]["id"]
client.put(f"/api/v1/projects/{project_id}", headers=admin_headers,
json={"name": f"审计用例-{suffix} 改名", "type": 1})
# 按项目 id 搜而不是按项目编号:PUT 是全量覆盖,测试请求没带编号,
# 更新那条审计里的编号是空的,用编号搜会漏掉它自己都要证明的那条。
data = self._logs(client, admin_headers, keyword=str(project_id), pageSize=50)
rows = [row for row in data["items"] if row["objectId"] == str(project_id)]
actions = {row["action"] for row in rows}
assert {"create", "update"} <= actions, actions
for row in rows:
assert row["accountName"] and row["objectType"] == "project"
assert row["objectName"] and row["ok"] is True and row["ip"] is not None
client.request("DELETE", f"/api/v1/projects/{project_id}", headers=admin_headers)
def test_a_refused_write_is_logged_with_the_reason(self, client, admin_headers):
missing = client.request("DELETE", "/api/v1/projects/99999999", headers=admin_headers)
assert missing.status_code == 404
rows = [row for row in self._logs(client, admin_headers, onlyFailures=True,
pageSize=20)["items"]
if row["objectId"] == "99999999"]
assert rows, "失败的写操作也是审计对象"
assert rows[0]["status"] == 404 and rows[0]["errorCode"] == "not_found"
def test_credentials_never_reach_the_audit_log(self, client, admin_headers):
"""审计表里绝不出现口令:脱敏发生在写入之前,不是靠查询时藏。"""
suffix = uuid.uuid4().hex[:8]
secret = f"AuditProbe@{suffix}"
created = client.post("/api/v1/org/accounts", headers=admin_headers, json={
"account": f"auditprobe{suffix}", "displayName": "审计脱敏用例", "password": secret})
assert created.status_code == 200, created.text
account_id = created.json()["data"]["id"]
try:
assert self._logs(client, admin_headers, keyword=secret)["meta"]["total"] == 0, \
"按口令原文能搜到审计记录,说明脱敏没生效"
rows = [row for row in self._logs(client, admin_headers,
keyword="审计脱敏用例")["items"]
if row["objectId"] == str(account_id)]
assert rows, "账号创建本身要有审计记录"
detail = client.get(f"/api/v1/system/operation-logs/{rows[0]['id']}",
headers=admin_headers).json()["data"]["detail"]
assert detail["body"]["password"] == "***", detail["body"]
finally:
from app.db import SessionFactory
from app.models import Account, AccountIdentity, PermAccountRole
session = SessionFactory()()
try:
session.query(PermAccountRole).filter(
PermAccountRole.account_id == account_id).delete()
session.query(AccountIdentity).filter(
AccountIdentity.account_id == account_id).delete()
session.query(Account).filter(Account.id == account_id).delete()
session.commit()
finally:
session.close()
def test_purge_keeps_the_audit_row_after_the_object_is_gone(self, client, admin_headers):
"""对象销毁之后,审计行还得说得出被销毁的是什么。"""
suffix = uuid.uuid4().hex[:6].upper()
name = f"销毁留痕-{suffix}"
no = f"AUDL-{suffix}"
project_id = client.post("/api/v1/projects", headers=admin_headers, json={
"name": name, "type": 1, "projectNo": no}).json()["data"]["id"]
client.request("DELETE", f"/api/v1/projects/{project_id}", headers=admin_headers,
json={"reason": "留痕用例"})
assert client.request("DELETE", f"/api/v1/projects/{project_id}/purge",
headers=admin_headers,
json={"confirmName": no}).status_code == 200
rows = [row for row in self._logs(client, admin_headers, keyword=str(project_id),
pageSize=50)["items"]
if row["objectId"] == str(project_id)]
assert any(row["action"] == "purge" and row["objectName"] == name for row in rows), rows
def test_login_log_is_readable_through_the_same_page(self, client, admin_headers):
data = client.get("/api/v1/system/login-logs", headers=admin_headers,
params={"pageSize": 3}).json()["data"]
assert data["items"], "登录审计应该有记录"
assert {"account", "success", "ip", "createdAt"} <= set(data["items"][0])
def test_the_audit_page_has_its_own_permission_code(self, client, admin_headers, demo_accounts):
refused = client.get("/api/v1/system/operation-logs", headers=demo_accounts["wangwu"])
assert refused.status_code == 403, refused.text
assert "system:audit:view" in refused.json()["error"]["message"]
class TestCalculation:
def test_estimate_splits_tax_and_ladders_profit(self, client, admin_headers, budgeted_project):
body = client.post(f"/api/v1/finance/estimate/projects/{budgeted_project}/calculate",
headers=admin_headers).json()["data"]
profit = body["profit"]
# 11300000/1.13 = 10000000,2120000/1.09 = 2000000
assert profit["income_total"] == "12000000.00"
# 6780000/1.13 = 6000000,1060000/1.09 = 1000000
assert profit["purchase_total"] == "7000000.00"
assert profit["gross_a"] == "5000000.00"
assert profit["contribution_rate"]["defined"] is True
assert body["calc_version"]
def test_amounts_travel_as_strings(self, client, admin_headers, budgeted_project):
body = client.post(f"/api/v1/finance/budget/projects/{budgeted_project}/calculate",
headers=admin_headers).json()["data"]
assert isinstance(body["contract_amount"], str), "金额必须字符串出参,避免 JS 精度丢失"
def test_fund_plan_is_derived_and_interest_follows_negative_balance(
self, client, admin_headers, budgeted_project):
body = client.post(f"/api/v1/finance/budget/projects/{budgeted_project}/calculate",
headers=admin_headers).json()["data"]
months = body["fund_plan"]["months"]
assert months[0]["month"] == "2026-01"
assert months[0]["balance"] == "-6780000.00"
# 年利率 6%:6780000 × 6% / 12
assert months[0]["capital_interest"] == "33900.00"
assert body["fund_plan"]["peak_month"] == "2026-01"
class TestValidationGuard:
def test_unbalanced_budget_cannot_be_submitted(self, client, admin_headers):
suffix = uuid.uuid4().hex[:6].upper()
project_id = client.post("/api/v1/projects", headers=admin_headers, json={
"name": f"脏数据拦截-{suffix}", "type": 1, "projectNo": f"BAD-{suffix}",
"planStart": "2026-01", "planEnd": "2026-03",
}).json()["data"]["id"]
client.post(f"/api/v1/finance/budget/projects/{project_id}/lines/income",
headers=admin_headers,
json={"data": {"income_type": 1, "name": "设备", "include_amount": "113", "tax_rate": "13"}})
calc = client.post(f"/api/v1/finance/budget/projects/{project_id}/calculate",
headers=admin_headers).json()["data"]
assert calc["validation"]["passed"] is False
assert {issue["ruleId"] for issue in calc["validation"]["errors"]} >= {"PLAN-VAL-002"}
submit = client.post(f"/api/v1/finance/budget/projects/{project_id}/submit",
headers=admin_headers, json={"comment": "先试试"})
assert submit.status_code == 400
assert submit.json()["error"]["code"] == "validation_failed"
class TestApprovalFlow:
def test_submit_creates_a_running_instance(self, client, admin_headers, budgeted_project):
submit = client.post(f"/api/v1/finance/budget/projects/{budgeted_project}/submit",
headers=admin_headers, json={"comment": "请审批"})
assert submit.status_code == 200, submit.text
ctx_id = client.get(f"/api/v1/finance/budget/projects/{budgeted_project}/approval",
headers=admin_headers).json()["data"]["instances"][0]
assert ctx_id["status"] == "reviewing"
def test_flow_nodes_carry_candidates(self, client, admin_headers):
flows = client.get("/api/v1/approvals/flows", headers=admin_headers).json()["data"]
target = next(f for f in flows if f["businessModule"] == "budget" and f["status"] == "published")
detail = client.get(f"/api/v1/approvals/flows/{target['id']}", headers=admin_headers).json()["data"]
assert detail["errors"] == []
approve_nodes = [n for n in detail["nodes"] if n["nodeType"] == "approve"]
assert approve_nodes and all(n["candidates"] for n in approve_nodes)
def test_approve_every_node_until_approved(self, client, admin_headers, budgeted_project,
demo_accounts):
"""待办只发给被指派的人,所以逐轮换成"当前办理人"的身份把链走完。
超管看的是流程监控,不会替别人办待办,一路用 admin 点到底是不成立的假设。
"""
actors = [admin_headers] + [demo_accounts[name] for name in ("zhangsan", "lisi", "wangwu")]
for _ in range(12):
progressed = False
for headers in actors:
todo = client.get("/api/v1/approvals/todo", headers=headers).json()["data"]["items"]
mine = [t for t in todo if t["projectId"] == budgeted_project]
if not mine:
continue
progressed = True
for task in mine:
acted = client.post(f"/api/v1/approvals/tasks/{task['taskId']}/act",
headers=headers,
json={"action": "approve", "comment": "同意"})
assert acted.status_code == 200, acted.text
if not progressed:
break
else:
pytest.fail("审批链未在 12 轮内收敛")
detail = client.get(f"/api/v1/finance/budget/projects/{budgeted_project}/approval",
headers=admin_headers).json()["data"]
assert detail["instances"][0]["status"] == "approved"
assert {record["action"] for record in detail["records"]} >= {"submit", "approve"}
assert all(record["operatorName"] for record in detail["records"])
def test_approved_budget_projects_the_projection_onto_the_project(
self, client, admin_headers, budgeted_project):
detail = client.get(f"/api/v1/projects/{budgeted_project}", headers=admin_headers).json()["data"]
assert detail["contractAmount"] not in (None, "", "0.00"), "合同额应回写到项目主档"
assert detail["calcVersion"]
assert detail["grossProfitRate"], "毛利率应回写"
def test_unknown_action_is_rejected(self, client, admin_headers, budgeted_project):
todo = client.get("/api/v1/approvals/todo", headers=admin_headers).json()["data"]["items"]
if not todo:
pytest.skip("当前无待办")
response = client.post(f"/api/v1/approvals/tasks/{todo[0]['taskId']}/act",
headers=admin_headers, json={"action": "teleport"})
assert response.status_code in (400, 422)
def _account_by_name(client, admin_headers, account: str) -> dict:
"""按账号名要点人。
别用"取列表第一页再挑"的写法:列表是按 id 排的,免登与同步的用例每跑一次就多建几个
账号,跑几轮之后种子里那几个人就被挤出第一页了,测试红得和代码一点关系都没有。
"""
items = client.get("/api/v1/org/accounts", headers=admin_headers,
params={"keyword": account, "pageSize": 50}).json()["data"]["items"]
return next(row for row in items if row["account"] == account)
class TestPermissionAndDataScope:
@pytest.mark.parametrize("account,expected_scope", [
("zhangsan", "本部门及下级"),
("lisi", "我参与的"),
])
def test_role_drives_data_scope(self, client, admin_headers, demo_accounts, account,
expected_scope):
headers = login(client, account)
body = client.get("/api/v1/projects", headers=headers).json()
assert body["ok"] is True
scope = body["data"]["scope"]
assert scope["unlimited"] is False
assert expected_scope in scope["description"]
def test_business_role_cannot_read_role_admin(self, client, demo_accounts):
response = client.get("/api/v1/system/roles", headers=login(client, "zhangsan"))
assert response.status_code == 403
assert response.json()["ok"] is False
def test_business_role_menu_tree_is_pruned(self, client, demo_accounts):
menus = client.get("/api/v1/auth/menus", headers=login(client, "zhangsan")).json()["data"]
assert "系统管理" not in {node["name"] for node in menus}
def test_explain_shows_the_effective_range(self, client, admin_headers, demo_accounts):
target = _account_by_name(client, admin_headers, "lisi")
body = client.post("/api/v1/system/data-policies/explain", headers=admin_headers,
json={"accountId": target["id"], "module": "project"})
assert body.status_code == 200, body.text
data = body.json()["data"]
assert data["unlimited"] is False and data["description"]
def test_unregistered_module_denies_instead_of_allowing(self, client, admin_headers,
demo_accounts):
target = _account_by_name(client, admin_headers, "lisi")
data = client.post("/api/v1/system/data-policies/explain", headers=admin_headers,
json={"accountId": target["id"], "module": "not_a_module"}
).json()["data"]
assert data["unlimited"] is False
assert "默认拒绝" in data["description"]
def test_seeded_roles_are_present(self, client, admin_headers):
codes = {row["code"] for row in client.get("/api/v1/system/roles",
headers=admin_headers).json()["data"]}
assert {"super_admin", "project_owner", "business", "finance", "leader"} <= codes
class TestOrgAndConfig:
def test_org_unit_tree(self, org_tree):
assert "children" in org_tree[0]
def test_accounts_are_paged(self, client, admin_headers):
"""分页只管"每页别超"与"总数别骗人"。
以前顺手断言 ``total >= 4``,那是"演示账号也在库里"的前提;本地账号收敛成一个
之后这个前提就没了——账号总数由部署与同步说了算,不该拿来当分页的用例前提。
"""
data = client.get("/api/v1/org/accounts", headers=admin_headers,
params={"pageSize": 2}).json()["data"]
assert len(data["items"]) <= 2 and data["meta"]["total"] >= 1
whole = client.get("/api/v1/org/accounts", headers=admin_headers,
params={"pageSize": 100}).json()["data"]
builtin = next(row for row in whole["items"] if row["account"] == ADMIN)
assert builtin["canLoginLocally"] is True, (
"内置本地账号必须能在本机登录,否则 Hub 一挂就没人进得来")
def _hard_delete_account(account_id: int) -> None:
"""把用例造的账号连同人-角色、兼岗一起删掉。
账号不像演示项目可以留在库里当数据——人员选择器、分配角色弹窗会一直把它摊出来,
跑几轮之后界面上全是 roletest_xxx。
"""
from sqlalchemy import delete
from app.db import SessionFactory
from app.models import Account, AccountIdentity, PermAccountRole
session = SessionFactory()()
try:
session.execute(delete(PermAccountRole).where(PermAccountRole.account_id == account_id))
session.execute(delete(AccountIdentity).where(AccountIdentity.account_id == account_id))
session.execute(delete(Account).where(Account.id == account_id))
session.commit()
finally:
session.close()
def _hard_delete_role(role_id: int) -> None:
"""把用例造的临时角色连权限点一起抹掉。
接口删除是软删,跑几轮库里就攒一排 is_deleted=1 的 roletest_xxx;
``perm_role.code`` 还有唯一约束,这些残行迟早会让"删掉的角色编码建不回来"。
"""
from sqlalchemy import delete
from app.db import SessionFactory
from app.models import PermRole, PermRoleNode
session = SessionFactory()()
try:
session.execute(delete(PermRoleNode).where(PermRoleNode.role_id == role_id))
session.execute(delete(PermRole).where(PermRole.id == role_id))
session.commit()
finally:
session.close()
def _node_ids(*codes: str) -> list[int]:
"""按权限码取目录节点 id,省得为了配角色先去要 system:permission:view。"""
from sqlalchemy import select
from app.db import SessionFactory
from app.models import PermNode
session = SessionFactory()()
try:
return list(session.execute(select(PermNode.id).where(PermNode.code.in_(codes)))
.scalars().all())
finally:
session.close()
class TestAccountRoleAssignment:
"""给人员配角色。
统一身份把人整批镜像过来之后,本地真正要动的只有"这个人能看什么"。所以配角色
既要有一条自己的入口(不必把整份档案填一遍),也要在没有角色管理权限的人手里
用得起来——能管人不等于能改角色里的权限点。
"""
@pytest.fixture()
def temp_account(self, temp_person):
"""大多数用例只需要一个人,这里给一个现成的。"""
return temp_person()
@pytest.fixture()
def temp_person(self, client, admin_headers):
"""造一个用完就删的本地账号;需要两个以上人的用例用这个工厂。"""
made: list[int] = []
def maker(display_name: str = "角色测试账号") -> tuple[int, str]:
account = f"roletest_{uuid.uuid4().hex[:8]}"
created = client.post("/api/v1/org/accounts", headers=admin_headers, json={
"account": account, "displayName": display_name,
"password": PERSON_PASSWORD}).json()
assert created["ok"], created.text
made.append(created["data"]["id"])
return created["data"]["id"], account
try:
yield maker
finally:
for account_id in made:
_hard_delete_account(account_id)
@pytest.fixture()
def temp_role(self, client, admin_headers):
def _make(enabled: bool = True) -> dict:
code = f"roletest_{uuid.uuid4().hex[:8]}"
created = client.post("/api/v1/system/roles", headers=admin_headers, json={
"code": code, "name": f"角色测试_{code[-6:]}", "enabled": enabled}).json()
assert created["ok"], created.text
return {"id": created["data"]["id"], "code": code}
made: list[int] = []
def maker(enabled: bool = True) -> dict:
row = _make(enabled)
made.append(row["id"])
return row
try:
yield maker
finally:
for role_id in made:
_hard_delete_role(role_id)
def test_role_options_are_readable_without_role_admin(self, client, admin_headers,
temp_account, temp_role):
"""能管人就该看见候选角色,但不该顺手看见角色管理。"""
gate = temp_role()
assert client.put(f"/api/v1/system/roles/{gate['id']}/permissions", headers=admin_headers,
json={"nodeIds": _node_ids("org:person:view", "org:person:edit")}
).json()["ok"] is True
target, account = temp_account
assert client.put(f"/api/v1/org/accounts/{target}/roles", headers=admin_headers,
json={"roleIds": [gate["id"]]}).json()["ok"] is True
headers = login(client, account, PERSON_PASSWORD)
options = client.get("/api/v1/org/accounts/role-options", headers=headers).json()
assert options["ok"] is True, options.text
assert {gate["code"]} <= {row["code"] for row in options["data"]}, \
"候选角色清单要包含刚建的这个角色"
assert client.get("/api/v1/system/roles", headers=headers).status_code == 403, \
"看候选角色不该连带把角色的权限点也放开"
def test_assign_roles_writes_membership_and_filter(self, client, admin_headers,
temp_account, temp_role):
"""分配角色只动角色;同步来的一整批人要能被"只看未分配角色"挑出来。"""
account_id, account = temp_account
role = temp_role()
listed = client.get("/api/v1/org/accounts", headers=admin_headers,
params={"keyword": account}).json()["data"]["items"]
row = next(item for item in listed if item["account"] == account)
assert row["roles"] == []
assert client.get("/api/v1/org/accounts", headers=admin_headers,
params={"keyword": account, "unassigned": True}
).json()["data"]["meta"]["total"] == 1
updated = client.put(f"/api/v1/org/accounts/{account_id}/roles", headers=admin_headers,
json={"roleIds": [role["id"]]}).json()
assert updated["ok"] is True, updated.text
assert [item["code"] for item in updated["data"]["roles"]] == [role["code"]]
detail = client.get(f"/api/v1/org/accounts/{account_id}", headers=admin_headers).json()["data"]
assert {item["code"] for item in detail["roles"]} == {role["code"]}
assert client.get("/api/v1/org/accounts", headers=admin_headers,
params={"keyword": account, "unassigned": True}
).json()["data"]["meta"]["total"] == 0, "配过角色就该从未分配名单里消失"
def test_assign_roles_rejects_unknown_and_disabled(self, client, admin_headers,
temp_account, temp_role):
account_id, _ = temp_account
unknown = client.put(f"/api/v1/org/accounts/{account_id}/roles", headers=admin_headers,
json={"roleIds": [999_999_999]}).json()
assert unknown["ok"] is False and unknown["error"]["code"] == "unknown_role"
dormant = temp_role(enabled=False)
rejected = client.put(f"/api/v1/org/accounts/{account_id}/roles", headers=admin_headers,
json={"roleIds": [dormant["id"]]}).json()
assert rejected["ok"] is False and rejected["error"]["code"] == "role_disabled"
assert client.put(f"/api/v1/system/roles/{dormant['id']}", headers=admin_headers,
json={"code": dormant["code"], "name": "重新启用的测试角色",
"enabled": True}).json()["ok"] is True
assert client.put(f"/api/v1/org/accounts/{account_id}/roles", headers=admin_headers,
json={"roleIds": [dormant["id"]]}).json()["ok"] is True
def test_editing_account_keeps_the_system_admin_flag(self, client, admin_headers):
"""编辑档案时不传 isSystemAdmin,等于"这次不动它",不是"把他降成普通人"。"""
account = f"roletest_{uuid.uuid4().hex[:8]}"
created = client.post("/api/v1/org/accounts", headers=admin_headers, json={
"account": account, "displayName": "超管测试账号", "isSystemAdmin": True}).json()
assert created["ok"] is True, created.text
account_id = created["data"]["id"]
try:
body = {"account": account, "displayName": "超管测试账号改过名", "remark": "只是改个备注"}
assert client.put(f"/api/v1/org/accounts/{account_id}", headers=admin_headers,
json=body).json()["ok"] is True
detail = client.get(f"/api/v1/org/accounts/{account_id}", headers=admin_headers).json()["data"]
assert detail["isSystemAdmin"], "漏传一个字段就把系统管理员抹掉,是没人能接受的丢权限"
body["isSystemAdmin"] = False
assert client.put(f"/api/v1/org/accounts/{account_id}", headers=admin_headers,
json=body).json()["ok"] is True
detail = client.get(f"/api/v1/org/accounts/{account_id}", headers=admin_headers).json()["data"]
assert not detail["isSystemAdmin"], "明说要收回,就要收得掉(本机还有内置超管兜底)"
finally:
_hard_delete_account(account_id)
def test_person_manager_cannot_grant_the_system_admin_flag(self, client, admin_headers,
temp_person, temp_role):
"""能改档案不该等于能给自己发一张万能卡。"""
gate = temp_role()
assert client.put(f"/api/v1/system/roles/{gate['id']}/permissions", headers=admin_headers,
json={"nodeIds": _node_ids("org:person:edit", "org:person:view")}
).json()["ok"] is True
editor_id, editor = temp_person("能管人的账号")
assert client.put(f"/api/v1/org/accounts/{editor_id}/roles", headers=admin_headers,
json={"roleIds": [gate["id"]]}).json()["ok"] is True
victim_id, victim = temp_person("被下手的账号")
headers = login(client, editor, PERSON_PASSWORD)
denied = client.put(f"/api/v1/org/accounts/{victim_id}", headers=headers, json={
"account": victim, "displayName": "被升成超管", "isSystemAdmin": True})
assert denied.status_code == 403, denied.text
detail = client.get(f"/api/v1/org/accounts/{victim_id}", headers=admin_headers).json()["data"]
assert not detail["isSystemAdmin"]
@staticmethod
def _role_codes(client, headers, account_id: int) -> set[str]:
body = client.get(f"/api/v1/org/accounts/{account_id}", headers=headers).json()
assert body["ok"] is True, body.text
return {item["code"] for item in body["data"]["roles"]}
def test_batch_append_leaves_existing_roles_alone(self, client, admin_headers,
temp_person, temp_role):
"""批量追加最怕顺手改掉别人原有的角色。"""
keeper = temp_role()
extra = temp_role()
loaded, _ = temp_person("批量已有角色的人")
fresh, _ = temp_person("批量干净的人")
assert client.put(f"/api/v1/org/accounts/{loaded}/roles", headers=admin_headers,
json={"roleIds": [keeper["id"]]}).json()["ok"] is True
result = client.post("/api/v1/org/accounts/roles/batch", headers=admin_headers, json={
"accountIds": [loaded, fresh, loaded], "mode": "append", "roleIds": [extra["id"]]}).json()
assert result["ok"] is True, result.text
assert result["data"] == {"accounts": 2, "affected": 2, "added": 2, "removed": 0}, \
"重复勾选要在服务端去重,别把同一个人算两次"
assert self._role_codes(client, admin_headers, loaded) == {keeper["code"], extra["code"]}
assert self._role_codes(client, admin_headers, fresh) == {extra["code"]}
def test_batch_remove_and_replace_do_exactly_what_they_say(self, client, admin_headers,
temp_person, temp_role):
"""移除只摘指定的,覆盖则整份换掉:两条路的差别必须能被测出来。"""
first, second = temp_role(), temp_role()
account_id, _ = temp_person("批量方式的人")
assert client.put(f"/api/v1/org/accounts/{account_id}/roles", headers=admin_headers,
json={"roleIds": [first["id"], second["id"]]}).json()["ok"] is True
removed = client.post("/api/v1/org/accounts/roles/batch", headers=admin_headers, json={
"accountIds": [account_id], "mode": "remove", "roleIds": [first["id"]]}).json()
assert removed["ok"] is True, removed.text
assert removed["data"]["removed"] == 1 and removed["data"]["added"] == 0
assert self._role_codes(client, admin_headers, account_id) == {second["code"]}
replaced = client.post("/api/v1/org/accounts/roles/batch", headers=admin_headers, json={
"accountIds": [account_id], "mode": "replace", "roleIds": [first["id"]]}).json()
assert replaced["ok"] is True, replaced.text
assert self._role_codes(client, admin_headers, account_id) == {first["code"]}, \
"覆盖没勾上的那个角色就该被摘掉"
cleared = client.post("/api/v1/org/accounts/roles/batch", headers=admin_headers, json={
"accountIds": [account_id], "mode": "replace", "roleIds": []}).json()
assert cleared["ok"] is True, cleared.text
assert self._role_codes(client, admin_headers, account_id) == set()
def test_batch_by_filter_hits_exactly_the_people_the_list_shows(self, client, admin_headers,
temp_person, temp_role):
"""按筛选圈人是同步后的主路径:弹窗上看到几个人,就得动几个人。"""
tag = uuid.uuid4().hex[:6]
ids = [temp_person(f"圈人{tag}甲")[0], temp_person(f"圈人{tag}乙")[0]]
params = {"keyword": tag, "unassigned": True}
total = client.get("/api/v1/org/accounts", headers=admin_headers,
params=params).json()["data"]["meta"]["total"]
assert total == 2
role = temp_role()
result = client.post("/api/v1/org/accounts/roles/batch", headers=admin_headers, json={
"target": {"keyword": tag, "unassigned": True}, "mode": "append",
"roleIds": [role["id"]]}).json()
assert result["ok"] is True, result.text
assert result["data"]["accounts"] == total == 2
assert client.get("/api/v1/org/accounts", headers=admin_headers,
params=params).json()["data"]["meta"]["total"] == 0, \
"整批配完,「只看未分配角色」里就该一个不剩"
for account_id in ids:
assert self._role_codes(client, admin_headers, account_id) == {role["code"]}
def test_batch_guardrails_refuse_ambiguous_and_impossible_targets(self, client, admin_headers,
temp_person, temp_role):
"""批量是把双刃剑:圈错人、圈错角色,都要在写库之前挡下来。"""
account_id, _ = temp_person("批量护栏的人")
role = temp_role()
def reject(payload) -> str:
body = client.post("/api/v1/org/accounts/roles/batch", headers=admin_headers,
json=payload).json()
assert body["ok"] is False, (payload, body)
return body["error"]["code"]
assert reject({"mode": "append", "roleIds": [role["id"]]}) == "pick_target"
assert reject({"accountIds": [account_id], "target": {},
"mode": "append", "roleIds": [role["id"]]}) == "pick_target"
assert reject({"accountIds": [account_id], "mode": "teleport",
"roleIds": [role["id"]]}) == "invalid_mode"
assert reject({"accountIds": [account_id], "mode": "append",
"roleIds": []}) == "empty_roles"
assert reject({"accountIds": [account_id], "mode": "remove",
"roleIds": []}) == "empty_roles"
assert reject({"target": {"keyword": f"没有这个人{uuid.uuid4().hex}"},
"mode": "append", "roleIds": [role["id"]]}) == "empty_target"
assert reject({"accountIds": [999_999_999], "mode": "append",
"roleIds": [role["id"]]}) == "unknown_account"
assert reject({"accountIds": [account_id], "mode": "append",
"roleIds": [999_999_999]}) == "unknown_role"
dormant = temp_role(enabled=False)
assert reject({"accountIds": [account_id], "mode": "append",
"roleIds": [dormant["id"]]}) == "role_disabled"
# 停用角色已经挂在人身上时,"移除"是清理,这条路要放行
def flip(enabled: bool):
return client.put(f"/api/v1/system/roles/{dormant['id']}", headers=admin_headers,
json={"code": dormant["code"], "name": "停用测试角色",
"enabled": enabled}).json()["ok"] is True
assert flip(True)
assert client.put(f"/api/v1/org/accounts/{account_id}/roles", headers=admin_headers,
json={"roleIds": [dormant["id"]]}).json()["ok"] is True
assert flip(False)
removed = client.post("/api/v1/org/accounts/roles/batch", headers=admin_headers, json={
"accountIds": [account_id], "mode": "remove", "roleIds": [dormant["id"]]}).json()
assert removed["ok"] is True, removed.text
assert self._role_codes(client, admin_headers, account_id) == set()
def test_batch_needs_people_edit_permission(self, client, admin_headers,
temp_person, temp_role):
"""只有查看权的人连批量都不该敲得开——批量一次动的人比单人分配多得多。"""
gate = temp_role()
assert client.put(f"/api/v1/system/roles/{gate['id']}/permissions", headers=admin_headers,
json={"nodeIds": _node_ids("org:person:view")}
).json()["ok"] is True
viewer_id, viewer = temp_person("只能看人员名单的账号")
assert client.put(f"/api/v1/org/accounts/{viewer_id}/roles", headers=admin_headers,
json={"roleIds": [gate["id"]]}).json()["ok"] is True
victim_id, _ = temp_person("差点被批量的人")
headers = login(client, viewer, PERSON_PASSWORD)
denied = client.post("/api/v1/org/accounts/roles/batch", headers=headers, json={
"accountIds": [victim_id], "mode": "append", "roleIds": [gate["id"]]})
assert denied.status_code == 403, denied.text
assert self._role_codes(client, admin_headers, victim_id) == set()
class TestDataPolicyFamily:
"""项目这一族(项目列表 + 概算/预算/结算/决算)只吃一条数据口径。
从前 seed 按模块各铺一条,一个角色三张一模一样的卡片,还会因为"角色已经配过权限
节点就不再校准"而种漏;现在族代表那一条管住整族,成员模块上单独配的策略优先。
"""
@staticmethod
def _policy(module: str, scope_type: str = "all"):
from types import SimpleNamespace
return SimpleNamespace(module=module, effect="allow", scope_type=scope_type,
valid_from="", valid_to="")
def test_family_default_reaches_every_member_module(self):
from app.service import data_scope
family = self._policy("project")
picked, inherited = data_scope._policies_for_module(
[family], data_scope.spec_for("budget"), "budget")
assert picked == [family] and inherited is True
def test_module_specific_policy_wins_instead_of_becoming_a_union(self):
"""专属优先而不是并集:否则"预算只看本部门"会被项目那条"全部数据"重新撑开。"""
from app.service import data_scope
family, mine = self._policy("project"), self._policy("budget", "unit")
picked, inherited = data_scope._policies_for_module(
[family, mine], data_scope.spec_for("budget"), "budget")
assert picked == [mine] and inherited is False
def test_a_seeded_role_needs_exactly_one_policy_for_the_family(self, client, admin_headers):
"""授权页不该再出现"同一角色 × 每个模块"的重复卡片。"""
from app.service import data_scope
rows = client.get("/api/v1/system/data-policies", headers=admin_headers).json()["data"]
family = set(data_scope.policy_covers("project"))
by_role: dict[int, list] = {}
for row in rows:
if row["subjectType"] == "role" and row["module"] in family:
by_role.setdefault(row["subjectId"], []).append(row)
assert by_role, "内置角色的默认数据口径不该是空的"
for role_id, items in by_role.items():
assert len(items) == 1, (role_id, [row["name"] for row in items])
assert items[0]["module"] == "project", items[0]["name"]
def test_budget_explains_itself_with_the_project_scope(self, client, admin_headers,
demo_accounts):
target = _account_by_name(client, admin_headers, "zhangsan")
def explain(module: str) -> dict:
body = client.post("/api/v1/system/data-policies/explain", headers=admin_headers,
json={"accountId": target["id"], "module": module})
assert body.status_code == 200, body.text
return body.json()["data"]
project, budget = explain("project"), explain("budget")
assert project["description"] in budget["description"]
assert "沿用「项目列表」的口径" in budget["description"]
class TestDescendantUnitIds:
"""``本部门及下级`` 是靠 ``org_unit.path`` 前缀匹配算的,前缀算错就往越权那边倒。"""
def test_a_bare_or_slashless_path_cannot_be_used_as_a_prefix(self):
from types import SimpleNamespace
from app.service.data_scope import _descendant_prefix
# 列默认值就是 "/":拿它当 LIKE 前缀等于 "/% ",整棵树都成了自己的下级
assert _descendant_prefix(SimpleNamespace(path="/", id=42)) == "/42/"
assert _descendant_prefix(SimpleNamespace(path="", id=7)) == "/7/"
# 少写结尾斜杠的 "/1/2" 会把同级 20/21/…29 一起前缀匹配进来
assert _descendant_prefix(SimpleNamespace(path="/1/2", id=2)) == "/1/2/"
assert _descendant_prefix(SimpleNamespace(path="/1/2/", id=2)) == "/1/2/"
def test_a_sibling_is_not_counted_as_someones_child(self, client):
"""路径形状照迁移脚本那种"没有结尾斜杠"的写法造,同级不该被算进下级。"""
from app.db import SessionFactory
from app.models.org import OrgUnit
from app.service.data_scope import descendant_unit_ids
namespace = "/900000001" # 真实路径由真实 id 拼成,不会撞到这个段
session = SessionFactory()()
try:
parent = OrgUnit(name="__探针父__", code="__probe_p__")
sibling = OrgUnit(name="__探针同级__", code="__probe_s__")
child = OrgUnit(name="__探针子__", code="__probe_c__")
root = OrgUnit(name="__探针无路径__", code="__probe_n__")
session.add_all([parent, sibling, child, root])
session.flush()
parent.path, sibling.path, child.path = (
f"{namespace}/2", f"{namespace}/20", f"{namespace}/2/7")
root.path = "/" # 列默认值,等价于脚本直插、没跑过路径重算
session.flush()
assert descendant_unit_ids(session, [parent.id]) == [parent.id, child.id]
# path 还是 "/" 的部门只该看见它自己,而不是整棵组织树
assert descendant_unit_ids(session, [root.id]) == [root.id]
finally:
session.rollback()
session.close()
def test_configs_expose_the_calc_version(self, client, admin_headers):
configs = client.get("/api/v1/system/configs", headers=admin_headers).json()["data"]
assert configs
class TestCalcRulesApi:
"""计算口径从前端的读写:读得到、改得动、非法值进不来、改完立刻生效。
这几条是"配置文件里不再留计算规则"之后的替代保障:口径改错等于改算钱的算法,
校验与生效路径必须有测试钉住。用例跑完把库里的值原样还回去——这是台共用的开发库。
"""
@pytest.fixture(autouse=True)
def _restore_rules(self, client, admin_headers):
before = client.get("/api/v1/system/calc-rules", headers=admin_headers).json()["data"]
snapshot = {rule["code"]: rule["stored"]
for section in before["sections"] for rule in section["rules"]}
yield
client.put("/api/v1/system/calc-rules", headers=admin_headers, json={"values": snapshot})
def _rules(self, client, admin_headers) -> dict[str, dict]:
data = client.get("/api/v1/system/calc-rules", headers=admin_headers).json()["data"]
return {rule["code"]: rule for section in data["sections"] for rule in section["rules"]}
def test_every_rule_comes_with_the_control_it_needs(self, client, admin_headers):
"""页面照着这份渲染控件,所以枚举必须带候选值、数字必须带范围。"""
rules = self._rules(client, admin_headers)
assert len(rules) == 14, sorted(rules)
assert {"calc.version", "calc.rounding", "calc.tax_from_complement"} <= set(rules)
assert rules["calc.rounding"]["choices"], "枚举口径没有候选值,页面只能裸输"
assert rules["calc.money_scale"]["min"] == 0
assert rules["calc.tax_from_complement"]["kind"] == "bool"
assert all(rule["configured"] for rule in rules.values()), "startup seed 该把 14 条都补齐"
assert not any(rule["normalized"] for rule in rules.values()), "库里的值都应通过校验"
assert not any(rule["code"] == "finance.company_manage_fee_rate" for rule in rules.values())
def test_legacy_duplicate_configs_are_gone(self, client, admin_headers):
"""老那两条"界面上有、内核从不读"的重复参数已并进 calc.*,不能留着两套口径。"""
configs = client.get("/api/v1/system/configs", headers=admin_headers).json()["data"]
codes = {row["code"] for row in configs}
assert not {"finance.company_manage_fee_rate", "budget.travel_business_limit_rate"} & codes
assert "calc.company_manage_fee_rate" in codes and "calc.travel_business_limit_rate" in codes
def test_business_param_page_is_not_an_entry_for_calc_rules(self, client, admin_headers):
body = client.put("/api/v1/system/configs/calc.rounding", headers=admin_headers,
json={"value": "DOWN"})
assert body.status_code == 409, body.text
assert body.json()["error"]["code"] == "use_calc_rules"
assert self._rules(client, admin_headers)["calc.rounding"]["value"] == "HALF_UP"
def test_invalid_value_writes_nothing(self, client, admin_headers):
"""整页校验:一条不合法就一条都不写,不能留下改了一半的口径。"""
body = client.put("/api/v1/system/calc-rules", headers=admin_headers, json={"values": {
"calc.company_manage_fee_rate": "3.5", "calc.rounding": "HALF_CENTIMETER"}})
assert body.status_code == 409, body.text
message = body.json()["error"]["message"]
assert "舍入方式" in message, message
rules = self._rules(client, admin_headers)
assert rules["calc.company_manage_fee_rate"]["value"] == "2.8"
assert rules["calc.rounding"]["value"] == "HALF_UP"
def test_out_of_range_scale_is_rejected(self, client, admin_headers):
body = client.put("/api/v1/system/calc-rules", headers=admin_headers,
json={"values": {"calc.money_scale": "99"}})
assert body.status_code == 409
assert "不能大于" in body.json()["error"]["message"]
def test_saved_rule_reaches_the_engine_at_once(self, client, admin_headers, budgeted_project):
"""保存即生效:不用重启,下一次试算就按新口径算,版本号也一起走。"""
baseline = client.post(f"/api/v1/finance/estimate/projects/{budgeted_project}/calculate",
headers=admin_headers).json()["data"]["profit"]
assert baseline["company_manage"] == "336000.00", baseline # 12000000 × 2.8%
body = client.put("/api/v1/system/calc-rules", headers=admin_headers, json={"values": {
"calc.company_manage_fee_rate": "5", "calc.version": "2026.11-test"}})
assert body.status_code == 200, body.text
assert body.json()["data"]["version"] == "2026.11-test"
after = client.post(f"/api/v1/finance/estimate/projects/{budgeted_project}/calculate",
headers=admin_headers).json()["data"]
assert after["profit"]["company_manage"] == "600000.00", after["profit"]
assert after["calc_version"] == "2026.11-test", "快照必须盖上新口径的版本号"
info = client.get("/api/v1/system/info", headers=admin_headers).json()["data"]
assert info["calcVersion"] == "2026.11-test"
assert info["companyManageFeeRate"] == 5.0
assert info["calcRulesChanged"] >= 1
assert client.get("/api/health").json()["calcVersion"] == "2026.11-test"
def test_zero_denominator_switch_flips_the_profit_rates(self, client, admin_headers,
budgeted_project):
"""零分母口径是开关能改的:改成 zero 之后未定义利润率变成 0(对账过渡期用)。"""
body = client.put("/api/v1/system/calc-rules", headers=admin_headers,
json={"values": {"calc.zero_denominator": "zero"}})
assert body.status_code == 200, body.text
assert self._rules(client, admin_headers)["calc.zero_denominator"]["value"] == "zero"
estimate = client.get(f"/api/v1/finance/estimate/projects/{budgeted_project}/revision",
headers=admin_headers).json()["data"]
assert estimate, "前置版本还在"
def test_calc_rule_page_is_a_separate_menu(self, client, admin_headers):
"""口径页有自己的权限码:能改业务参数不等于能改财务口径。"""
menus = client.get("/api/v1/bootstrap", headers=admin_headers).json()["data"]["menus"]
def walk(nodes):
for node in nodes:
yield node
yield from walk(node.get("children") or [])
paths = {node.get("path") for node in walk(menus)}
assert "/system/calc-rules" in paths, sorted(p for p in paths if p)