cmvr-visual/backend/tests/test_architecture_contract.py

207 lines
8.9 KiB
Python
Raw Permalink Normal View History

"""Refactoring must preserve the public API and existing database definition."""
import json
from copy import deepcopy
from pathlib import Path
import sys
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT))
def test_routes_and_mysql_metadata_are_unchanged():
from scripts.architecture_contract import capture_contract
expected = json.loads(
(Path(__file__).parent / "fixtures/engineering_contract.json").read_text(encoding="utf-8")
)
actual = capture_contract()
additions = {
"visual_shot_candidates",
"visual_shot_selections",
"visual_folders",
"visual_asset_folders",
"visual_workflow_variants",
"visual_quality_assessments",
}
assert set(actual["tables"]) == set(expected["tables"]) | additions
folder_columns = {
"visual_drafts": {"folder_id"},
"visual_jobs": {"folder_id", "output_folder_id"},
"visual_workflow_runs": {"folder_id", "output_folder_id"},
}
# 007/008只允许合同内的追加列;原列定义与历史fixture仍逐项比较。
editor_columns = {
"visual_drafts": {"editor_manifest": ("JSON", True), "caption_birth_intent": ("JSON", True)},
"visual_workflow_runs": {
"run_kind": ("VARCHAR(32)", False),
"output_goal": ("VARCHAR(16)", False),
"base_run_id": ("VARCHAR(32)", True),
"source_draft_version": ("INTEGER", True),
"plan_snapshot": ("JSON", True),
"result_manifest": ("JSON", True),
"apply_state": ("VARCHAR(16)", True),
"phase": ("VARCHAR(24)", True),
"prepared_plan": ("JSON", True),
},
"visual_workflow_steps": {
name: ("JSON", True) for name in ("recipe_json", "resolved_input_json", "result_json")
},
}
for name, old_table in expected["tables"].items():
current = deepcopy(actual["tables"][name])
folder_added = folder_columns.get(name, set())
editor_added = editor_columns.get(name, {})
added = folder_added | set(editor_added)
for column in current["columns"]:
if column["name"] in editor_added:
kind, nullable = editor_added[column["name"]]
assert column["type"] == kind
assert column["nullable"] is nullable
assert column["foreign_keys"] == []
if column["name"] in folder_added:
assert column["nullable"] is True
assert column["foreign_keys"] == ["visual_folders.id"]
assert column["type"] == "VARCHAR(32)"
assert {c["name"] for c in current["columns"]} == {
c["name"] for c in old_table["columns"]
} | added
current["columns"] = [c for c in current["columns"] if c["name"] not in added]
current["indexes"] = [i for i in current["indexes"] if not (set(i["columns"]) & added)]
assert current == old_table
# 用户管理只精确豁免新增端点,旧的路由、响应与表结构仍按历史合同检查。
delete_user = {
"path": "/api/auth/users/{user_id}",
"method": "DELETE",
"responses": ["204", "422"],
}
assert delete_user in actual["routes"]
change_username = {
"path": "/api/auth/username",
"method": "POST",
"responses": ["200", "422"],
}
assert change_username in actual["routes"]
editor_routes = [
{"path": "/api/editors/{draft_id}" + suffix, "method": method, "responses": responses}
for suffix, method, responses in (
("", "GET", ["200", "422"]),
("/save", "POST", ["200", "422"]),
("/from-run", "POST", ["200", "422"]),
("/plan", "POST", ["200", "422"]),
("/runs", "POST", ["202", "422"]),
("/apply", "POST", ["200", "422"]),
("/mode", "POST", ["200", "422"]),
("/dialogue/enable", "POST", ["200", "422"]),
("/dialogue/fork-prepared", "POST", ["201", "422"]),
("/dialogue/fork-cuts", "POST", ["200", "422"]),
("/captions/preview", "POST", ["200", "422"]),
("/runs/{run_id}/captions.srt", "GET", ["200", "422"]),
("/runs/{run_id}/turns/{shot_id}/review", "POST", ["200", "422"]),
)
]
assert all(r in actual["routes"] for r in editor_routes)
# 人工首帧恢复是显式新增的受保护命令,不能把其它工作流路由一并放宽。
restore_manual_frame = {
"path": "/api/workflow-runs/{id}/steps/{key}/restore-manual-frame",
"method": "POST",
"responses": ["200", "422"],
}
assert restore_manual_frame in actual["routes"]
assert [
r
for r in actual["routes"]
if not r["path"].startswith(("/api/stories", "/api/folders"))
and r not in (delete_user, change_username)
and r not in editor_routes
and r != restore_manual_frame
] == expected["routes"]
old_http, new_http = expected["http_contract"], actual["http_contract"]
for path, old_operations in old_http["operations"].items():
current = deepcopy(new_http["operations"][path])
if path == "/api/auth/users/{user_id}":
assert "204" in current.pop("delete")["responses"]
for method, operation in current.items():
if (
path in {"/api/assets", "/api/jobs", "/api/workflows", "/api/workflow-runs"}
and method == "get"
):
extra = [p for p in operation.get("parameters", []) if p["name"] == "folder_id"]
assert len(extra) == 1 and not extra[0].get("required", False)
operation["parameters"] = [
p for p in operation["parameters"] if p["name"] != "folder_id"
]
if path == "/api/shared-assets/{shared_id}/import" and method == "post":
assert not operation["requestBody"].get("required", False)
variants = operation["requestBody"]["content"]["application/json"]["schema"][
"anyOf"
]
assert variants == [{"$ref": "#/components/schemas/SharedImport"}, {"type": "null"}]
variants[0] = {"$ref": "#/components/schemas/EmptyPayload"}
assert current == old_operations
assert set(new_http["operations"]["/api/auth/username"]) == {"post"}
restore_operations = new_http["operations"][restore_manual_frame["path"]]
assert set(restore_operations) == {"post"}
assert restore_operations["post"]["requestBody"]["content"]["application/json"]["schema"] == {
"$ref": "#/components/schemas/RestoreManualFrame"
}
assert all(
p in old_http["operations"]
or p == "/api/auth/username"
or p in {r["path"] for r in editor_routes}
or p == restore_manual_frame["path"]
or p.startswith(("/api/stories", "/api/folders"))
for p in new_http["operations"]
)
optional_folder_fields = {
"AssetPatch": {"folder_ids"},
"BatchJob": {"folder_id", "output_folder_id"},
"BatchWorkflow": {"output_folder_id"},
"Body_upload_api_assets_post": {"folder_id"},
"DraftCreate": {"folder_id"},
"DraftPatch": {"folder_id"},
"RunCreate": {"output_folder_id"},
"Submit": {"folder_id", "output_folder_id"},
# 模型选择是向后兼容的可选字段;旧请求和历史fixture保持原结构。
"ShotParameters": {"profile"},
}
for group, components in old_http["components"].items():
for name, old_component in components.items():
current = deepcopy(new_http["components"][group][name])
added = optional_folder_fields.get(name, set()) if group == "schemas" else set()
for field in added:
assert field in current["properties"] and field not in current.get("required", [])
current["properties"].pop(field)
assert current == old_component
def test_asgi_entry_uses_the_shared_application_factory():
from app.bootstrap import create_app
from app.main import app, create_app as public_factory
assert public_factory is create_app
assert app.title == "CMVR Visual"
def test_pure_domain_does_not_import_http_database_or_io_adapters():
import ast
directory = ROOT / "backend/app/domain"
assert directory.is_dir()
forbidden = ("fastapi", "sqlalchemy", "httpx", "app.api", "app.services", "app.adapters")
for path in directory.rglob("*.py"):
tree = ast.parse(path.read_text(encoding="utf-8"))
for node in ast.walk(tree):
if isinstance(node, ast.Import):
imports = [alias.name for alias in node.names]
elif isinstance(node, ast.ImportFrom):
imports = [node.module or ""]
else:
continue
assert not any(
name == prefix or name.startswith(prefix + ".")
for name in imports
for prefix in forbidden
), path