it-architecture/backend/tests/test_api.py

405 lines
19 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.

"""End-to-end HTTP tests against the real ASGI app, including static hosting."""
from __future__ import annotations
import pytest
from fastapi.testclient import TestClient
@pytest.fixture()
def client(tmp_path, monkeypatch):
monkeypatch.setenv("DB_PATH", str(tmp_path / "api.db"))
from app import config
monkeypatch.setattr(config, "db_path", lambda: tmp_path / "api.db")
from app.main import app
with TestClient(app) as instance:
yield instance
# ------------------------------------------------------------------ read models
def test_health_and_seed(client):
assert client.get("/api/health").status_code == 200
assert client.get("/api/layers").json().__len__() == 3
assert len(client.get("/api/systems").json()) == 18
assert len(client.get("/api/flow-types").json()) == 6
assert len(client.get("/api/flows").json()) == 36
def test_graph_payload_is_animation_ready(client):
graph = client.get("/api/graph?days=7").json()
assert len(graph["nodes"]) == 18 and len(graph["edges"]) == 36
for edge in graph["edges"]:
# the frontend layout keys edges by endpoint key and animates on these numbers
assert edge["source_key"] and edge["target_key"]
assert edge["color"] and edge["line_style"]
assert edge["throughput_rps"] >= 0
assert edge["health"]["state"] in {"healthy", "watch", "risk", "idle"}
assert {node["rank"] for node in graph["nodes"]} == {node["tier"] for node in graph["nodes"]}
def test_metrics_endpoints_agree(client):
summary = client.get("/api/metrics/summary?days=7").json()
assert summary["totals"]["records"] > 0
hourly = client.get("/api/metrics/hourly?days=2").json()
assert hourly["points"], "hourly curve must not be empty"
live = client.get("/api/metrics/live").json()
assert len(live["flows"]) == 36
def test_flow_series_and_audit(client):
flow_id = client.get("/api/flows").json()[0]["id"]
series = client.get(f"/api/metrics/flows/{flow_id}?days=3").json()
assert series["points"]
assert client.get("/api/metrics/flows/999999").status_code == 404
assert isinstance(client.get("/api/audit?limit=10").json(), list)
# ------------------------------------------------------------------ writes over HTTP
def test_system_crud_and_validation_over_http(client):
created = client.post("/api/systems", json={"key": "http-demo", "name": "HTTP 系统", "layer_id": "base"})
assert created.status_code == 201
assert created.json()["layer_name"] == "底座(基础平台)"
assert client.post("/api/systems", json={"key": "http-demo", "name": "重复"}).status_code == 409
assert client.post("/api/systems", json={"key": "x", "name": "无层级", "layer_id": "ghost"}).status_code == 400
assert client.patch("/api/systems/http-demo", json={"status": "dev"}).json()["status"] == "dev"
assert client.patch("/api/systems/ghost", json={"status": "dev"}).status_code == 404
assert client.delete("/api/layers/base").status_code == 409, "层级仍被使用时不得删除"
assert client.delete("/api/systems/http-demo").json()["ok"] is True
def test_flow_guardrails_over_http(client):
base = {"source_key": "pms", "target_key": "kingdee", "flow_type_id": "core", "label": "HTTP 链路"}
created = client.post("/api/flows", json=base)
assert created.status_code == 201
assert created.json()["peak_hours"] == [9, 10, 11, 14, 15, 16, 17]
assert client.post("/api/flows", json=base).status_code == 409
assert client.post("/api/flows", json={**base, "target_key": "pms"}).status_code == 400
assert client.post("/api/flows", json={**base, "interval_sec": 1}).status_code == 422
flow_id = created.json()["id"]
assert client.patch(f"/api/flows/{flow_id}", json={"enabled": False}).json()["enabled"] is False
assert client.delete(f"/api/flows/{flow_id}").json()["ok"] is True
def test_editor_header_roundtrips_chinese_names(client):
"""The browser cannot put Chinese text in a header, so the client percent-encodes it."""
encoded = "%E5%BA%B7%E6%96%87%E6%99%B6"
client.post("/api/systems", json={"key": "hdr", "name": "请求头系统"}, headers={"X-Editor": encoded})
latest = client.get("/api/audit?limit=1").json()[0]
assert latest["actor"] == "康文晶"
def test_settings_patch_is_partial(client):
before = client.get("/api/settings").json()
updated = client.patch("/api/settings", json={"live_interval_sec": 30}).json()
assert updated["live_interval_sec"] == 30
assert updated["site_title"] == before["site_title"], "未提交的配置必须保留"
# ------------------------------------------------------------------ system fields
def test_impl_time_and_entry_flag_roundtrip(client):
"""实现时间 is free-form text and the jump switch decides who shows a shortcut."""
created = client.post(
"/api/systems",
json={"key": "entry-demo", "name": "入口系统", "url": "https://x.example.com",
"impl_time": "2024-06 上线", "entry_enabled": False},
)
assert created.status_code == 201
assert created.json()["impl_time"] == "2024-06 上线"
assert created.json()["entry_enabled"] is False
patched = client.patch("/api/systems/entry-demo", json={"entry_enabled": True}).json()
assert patched["entry_enabled"] is True
assert client.patch("/api/systems/entry-demo", json={"impl_time": " "}).json()["impl_time"] == ""
node = next(n for n in client.get("/api/graph").json()["nodes"] if n["key"] == "entry-demo")
assert node["impl_time"] == "" and node["entry_enabled"] is True
def test_seeded_systems_carry_the_new_fields(client):
for system in client.get("/api/systems").json():
assert system["impl_time"] == ""
assert system["entry_enabled"] is True, "默认所有系统都可以展示快捷入口"
def test_system_name_can_be_renamed_after_creation(client):
"""系统名称 is an ordinary field: the only rule is "not blank", the key never moves."""
renamed = client.patch("/api/systems/oa", json={"name": " OA(华智 OA · 新版) "})
assert renamed.status_code == 200
assert renamed.json()["name"] == "OA(华智 OA · 新版)"
assert renamed.json()["key"] == "oa", "改名不改主键"
assert client.patch("/api/systems/oa", json={"name": " "}).status_code == 422
# The flow read model carries its own copy of the name, so a rename has to reach it.
graph = client.get("/api/graph").json()
node = next(item for item in graph["nodes"] if item["key"] == "oa")
assert node["name"] == "OA(华智 OA · 新版)"
edge = next(item for item in graph["edges"] if item["source_key"] == "oa")
assert edge["source_name"] == "OA(华智 OA · 新版)"
audit = client.get("/api/audit?limit=5").json()
assert any("name" in entry["summary"] for entry in audit)
# Over-long names are cut rather than rejected; the field is capped, not precious.
assert len(client.patch("/api/systems/oa", json={"name": "x" * 200}).json()["name"]) == 80
# ------------------------------------------------------------------ read-only switch
def test_read_only_lock_blocks_content_writes(client):
assert client.patch("/api/settings", json={"editing_enabled": False}).json()["editing_enabled"] is False
blocked = [
client.post("/api/systems", json={"key": "locked", "name": "锁定测试"}),
client.patch("/api/systems/oa", json={"name": "改名"}),
client.delete("/api/systems/oa"),
client.post("/api/layers", json={"id": "locked", "name": "锁定层"}),
client.post("/api/flow-types", json={"id": "locked", "name": "锁定类型"}),
client.post("/api/flows", json={"source_key": "oa", "target_key": "oms",
"flow_type_id": "core", "label": "锁定链路"}),
client.put("/api/graph/layout", json={"items": [{"key": "oa", "x": 10, "y": 10}]}),
]
assert [response.status_code for response in blocked] == [423] * len(blocked)
assert "只读" in blocked[0].json()["detail"]
assert client.get("/api/systems").json(), "读取不受开关影响"
assert client.patch("/api/systems/oa", json={"name": "改名"}).status_code == 423
assert next(s for s in client.get("/api/systems").json() if s["key"] == "oa")["name"] != "改名"
def test_read_only_switch_can_be_turned_back_off(client):
"""Locking the platform must never lock the page that unlocks it."""
client.patch("/api/settings", json={"editing_enabled": False})
assert client.patch("/api/settings", json={"editing_enabled": True}).json()["editing_enabled"] is True
assert client.post("/api/systems", json={"key": "after", "name": "解锁后"}).status_code == 201
# A locked import is refused before anything is written.
client.patch("/api/settings", json={"editing_enabled": False})
payload = client.get("/api/backup").json()
assert client.post("/api/backup", json={**payload, "mode": "replace"}).status_code == 423
assert len(client.get("/api/systems").json()) == 19, "被拒绝的导入不得改动数据"
def test_live_metrics_still_run_while_locked(client):
"""实时推进 is a display clock, not a user edit, so it keeps ticking in read-only."""
client.patch("/api/settings", json={"editing_enabled": False})
assert client.post("/api/metrics/tick").status_code == 200
def test_matrix_endpoint_is_gone(client):
assert client.get("/api/metrics/matrix?days=7").status_code == 404
# ------------------------------------------------------------------ backup
def test_backup_export_then_merge_is_idempotent(client):
payload = client.get("/api/backup").json()
assert payload["systems"] and payload["data_flows"] and payload["schema_version"] == 1
result = client.post("/api/backup", json={**payload, "mode": "merge"}).json()
assert result["errors"] == []
assert len(client.get("/api/systems").json()) == 18, "按 id 合并不应产生重复"
def test_backup_replace_drops_orphans(client):
payload = client.get("/api/backup").json()
payload["systems"] = [s for s in payload["systems"] if s["key"] in {"oa", "pms"}]
result = client.post("/api/backup", json={**payload, "mode": "replace"}).json()
assert len(client.get("/api/systems").json()) == 2
assert any("端点系统不存在" in message for message in result["errors"])
# The restored graph must still render, and only the link whose endpoints both
# survived may remain.
graph = client.get("/api/graph?days=7").json()
assert len(graph["nodes"]) == 2
assert [(e["source_key"], e["target_key"]) for e in graph["edges"]] == [("pms", "oa")]
# History for the restored flow is rebuilt from its cadence rather than left blank.
assert graph["edges"][0]["health"]["records"] > 0
def test_backup_rejects_empty_payload(client):
assert client.post("/api/backup", json={}).status_code == 400
# ------------------------------------------------------------------ routing
def test_unknown_api_path_returns_json_404_not_the_spa_shell(client):
response = client.get("/api/does-not-exist")
assert response.status_code == 404
assert response.json() == {"detail": "接口不存在"}
def test_spa_routes_serve_the_built_app(client):
from app.config import WEB_DIST
if not WEB_DIST.is_dir():
pytest.skip("前端尚未构建,跳过静态托管校验")
for path in ("/", "/flow", "/panorama", "/config"):
response = client.get(path)
assert response.status_code == 200, path
assert "text/html" in response.headers["content-type"]
assert client.get("/favicon.svg").status_code == 200
# ------------------------------------------------------------------ canvas layout
def _node(client, key):
return next(node for node in client.get("/api/graph").json()["nodes"] if node["key"] == key)
def test_seeded_nodes_start_on_automatic_placement(client):
for node in client.get("/api/graph").json()["nodes"]:
assert node["flow_x"] is None and node["flow_y"] is None
def test_layout_endpoint_persists_positions_and_tier(client):
response = client.put(
"/api/graph/layout",
json={"items": [{"key": "oa", "x": 421.5, "y": 260, "tier": 2}]},
headers={"X-Editor": "%E5%BC%A0%E5%B7%A5"},
)
assert response.status_code == 200
assert response.json() == {"ok": True, "placed": 1, "cleared": 0, "moved": 1, "missing": []}
node = _node(client, "oa")
assert (node["flow_x"], node["flow_y"], node["tier"]) == (421.5, 260.0, 2)
audit = client.get("/api/audit").json()
assert len(audit) == 1, "a whole drag gesture is one audit entry, not one per card"
assert audit[0]["actor"] == "张工"
assert "手动摆放 1 个系统" in audit[0]["summary"]
def test_layout_tier_change_alone_keeps_the_dropped_position(client):
client.put("/api/graph/layout", json={"items": [{"key": "oa", "x": 120, "y": 80}]})
client.put("/api/graph/layout", json={"items": [{"key": "oa", "tier": 3}]})
node = _node(client, "oa")
assert (node["flow_x"], node["flow_y"], node["tier"]) == (120.0, 80.0, 3)
def test_layout_null_coordinates_return_a_card_to_auto_placement(client):
client.put("/api/graph/layout", json={"items": [{"key": "oa", "x": 10, "y": 20}]})
response = client.put("/api/graph/layout", json={"items": [{"key": "oa", "x": None, "y": None}]})
assert response.json()["cleared"] == 1
node = _node(client, "oa")
assert node["flow_x"] is None and node["flow_y"] is None
def test_layout_reset_clears_every_manual_position(client):
client.put("/api/graph/layout", json={"items": [
{"key": "oa", "x": 10, "y": 20}, {"key": "pms", "x": 30, "y": 40},
]})
assert client.post("/api/graph/layout/reset").json() == {"ok": True, "cleared": 2}
assert all(node["flow_x"] is None for node in client.get("/api/graph").json()["nodes"])
def test_layout_reports_unknown_keys_and_rejects_runaway_coordinates(client):
response = client.put("/api/graph/layout", json={"items": [{"key": "ghost", "x": 5, "y": 5}]})
assert response.json()["missing"] == ["ghost"]
assert client.put("/api/graph/layout", json={"items": [{"key": "oa", "x": 999999}]}).status_code == 422
assert client.put("/api/graph/layout", json={"items": [{"key": "oa", "tier": 99}]}).status_code == 422
def test_empty_layout_write_is_not_audited(client):
assert client.put("/api/graph/layout", json={"items": []}).status_code == 200
assert client.get("/api/audit").json() == []
def test_new_system_can_be_born_at_a_canvas_position(client):
created = client.post("/api/systems", json={
"key": "crm", "name": "CRM 客户管理", "layer_id": "dept", "dept": "云智销售部首",
"status": "dev", "tier": 2, "flow_x": 512, "flow_y": 640,
})
assert created.status_code == 201
node = _node(client, "crm")
assert (node["flow_x"], node["flow_y"]) == (512.0, 640.0)
def test_backup_round_trip_keeps_manual_positions(client):
client.put("/api/graph/layout", json={"items": [{"key": "oa", "x": 333, "y": 444}]})
snapshot = client.get("/api/backup").json()
client.post("/api/graph/layout/reset")
assert _node(client, "oa")["flow_x"] is None
assert client.post("/api/backup", json={**snapshot, "mode": "replace"}).status_code == 200
assert _node(client, "oa")["flow_x"] == 333.0
def test_read_only_lock_blocks_layout_reset(client):
"""恢复自动排列 rewrites every card, so the switch has to cover it too."""
client.put("/api/graph/layout", json={"items": [{"key": "oa", "x": 210, "y": 260}]})
client.patch("/api/settings", json={"editing_enabled": False})
blocked = client.post("/api/graph/layout/reset")
assert blocked.status_code == 423
assert "只读" in blocked.json()["detail"]
assert _node(client, "oa")["flow_x"] == 210.0, "被拒绝的重置不得清空手动位置"
assert client.patch("/api/settings", json={"editing_enabled": True}).status_code == 200
assert client.post("/api/graph/layout/reset").json() == {"ok": True, "cleared": 1}
def test_graph_payload_carries_topology_counts(client):
"""The flow canvas reads its own header numbers from the graph, metrics-free."""
graph = client.get("/api/graph").json()
counts = graph["counts"]
systems = client.get("/api/systems").json()
flows = client.get("/api/flows").json()
assert counts["systems"] == len(systems) == len(graph["nodes"])
assert counts["flows_total"] == len(flows)
assert counts["flows_enabled"] == sum(1 for flow in flows if flow["enabled"])
assert counts["tiers"] == len({system["tier"] for system in systems})
assert counts["linked_systems"] == sum(1 for node in graph["nodes"] if node["degree"])
client.post("/api/systems", json={"key": "crm_new", "name": "CRM 客户管理"})
created = client.post("/api/flows", json={"source_key": "oa", "target_key": "crm_new",
"flow_type_id": "core", "label": "新链路"})
assert created.status_code == 201
after = client.get("/api/graph").json()["counts"]
assert after["flows_total"] == counts["flows_total"] + 1
assert after["flows_enabled"] == counts["flows_enabled"] + 1
@pytest.mark.parametrize("style", ["elbow", "curve", "straight"])
def test_flow_route_style_round_trips_through_settings(client, style):
"""线型是汇报现场的偏好,要跟着设置走,刷新和换设备都不能丢。"""
assert client.patch("/api/settings", json={"flow_route_style": style}).json()["flow_route_style"] == style
assert client.get("/api/settings").json()["flow_route_style"] == style
def test_flow_route_style_rejects_unknown_value(client):
"""一个认不出的线型会让画布退回默认走线,不如在入口就拒绝。"""
assert client.patch("/api/settings", json={"flow_route_style": "curve"}).status_code == 200
assert client.patch("/api/settings", json={"flow_route_style": "spaghetti"}).status_code == 422
assert client.get("/api/settings").json()["flow_route_style"] == "curve"
def test_flow_type_accepts_dash_dot_line_style(client):
"""点划线 carries 定时任务 / 人工 in the legend, so both ends have to accept it."""
created = client.post(
"/api/flow-types", json={"id": "nightly", "name": "夜间批处理", "line_style": "dash-dot"}
)
assert created.status_code == 201
assert created.json()["line_style"] == "dash-dot"
payload = created.json() | {"name": "夜间批处理", "line_style": "solid"}
assert client.put("/api/flow-types/nightly", json=payload).json()["line_style"] == "solid"
def test_shipped_flow_types_follow_the_colour_legend(client):
"""图例承诺"蓝=调用、紫=鉴权取数、绿=消息、灰=定时、红=人工",种子数据必须真的这么画。"""
types = {item["id"]: item for item in client.get("/api/flow-types").json()}
assert types["core"]["color"].startswith("#1") and types["core"]["line_style"] == "solid"
assert types["cap"]["line_style"] == "solid", "底座能力调用是同步调用"
assert types["entry"]["line_style"] == "dashed", "消息推送是异步"
assert types["mcp"]["line_style"] == "dash-dot", "MCP 取数是定时"
assert types["archive"]["line_style"] == "dash-dot", "归档沉淀是定时"
assert types["auth"]["color"] == "#7c3aed" and types["core"]["color"] != types["cap"]["color"]