cmvr-visual/backend/tests/test_editors.py

475 lines
18 KiB
Python
Raw Permalink Normal View History

import pytest
from sqlalchemy import select
from app.models import WorkflowDraft
def spec():
return {
"schema_version": 2,
"shots": [{"key": "shot_1", "prompt": "test", "duration_frames": 120}],
}
async def test_editor_preview_save_cas_and_issues(system):
c = system.client
r = await c.post("/api/workflows", json={"name": "Editor", "spec": spec()})
assert r.status_code == 201, r.text
id = r.json()["id"]
preview = await c.get(f"/api/editors/{id}")
assert preview.status_code == 200, preview.text
m = preview.json()["manifest"]
async with system.app.state.db.session() as s:
assert (await s.get(WorkflowDraft, id)).editor_manifest is None
m["captions"]["cues"] = [
{
"id": "f" * 32,
"anchor": "absolute",
"start_frame": 0,
"end_frame": 999,
"text": "saved",
"text_override": True,
"timing_override": True,
}
]
body = {"expected_version": 1, "manifest": m}
url = f"/api/editors/{id}/save"
saved = await c.post(url, json=body, headers={"Idempotency-Key": "save"})
assert saved.status_code == 200, saved.text
assert saved.json()["version"] == 2
assert saved.json()["issues"]
again = await c.post(url, json=body, headers={"Idempotency-Key": "save"})
assert again.status_code == 200
assert again.json()["version"] == 2
conflict = await c.post(url, json=body, headers={"Idempotency-Key": "new"})
assert conflict.status_code == 409
async def test_editor_owner_and_csrf(system, other_client):
r = await system.client.post("/api/workflows", json={"name": "Editor", "spec": spec()})
id = r.json()["id"]
assert (await other_client.get(f"/api/editors/{id}")).status_code == 404
response = await system.client.post(
f"/api/editors/{id}/save",
json={"expected_version": 1, "manifest": {}},
headers={"X-CSRF-Token": "wrong"},
)
assert response.status_code == 403
async def test_editor_refs_server_provenance_and_frozen_restore(system, png_bytes):
from app.models import AssetReference, WorkflowRun, Submission
c = system.client
uploaded = await c.post("/api/assets", files={"file": ("ref.png", png_bytes, "image/png")})
assert uploaded.status_code == 201, uploaded.text
aid = uploaded.json()["id"]
r = await c.post("/api/workflows", json={"name": "Editor", "spec": spec()})
id = r.json()["id"]
m = (await c.get(f"/api/editors/{id}")).json()["manifest"]
sid = m["shot_ids"][0]
m["bindings"]["frame:" + sid] = {
"asset_id": aid,
"kind": "image",
"source": "generated",
"input_hash": "forged",
"sample_count": 1,
"duration_frames": 999999,
"duration_seconds": 999999.0,
}
response = await c.post(
f"/api/editors/{id}/save",
json={"expected_version": 1, "manifest": m},
headers={"Idempotency-Key": "save"},
)
assert response.status_code == 200, response.text
frozen = response.json()["manifest"]
binding = frozen["bindings"]["frame:" + sid]
assert len(binding["sha256"]) == 64
assert binding["sha256"] != "0" * 64
assert binding.get("input_hash") is None
assert binding["source"] == "manual"
assert binding.get("sample_count") is None
assert binding.get("duration_frames") is None
assert binding.get("duration_seconds") is None
async with system.app.state.db.session() as s:
d = await s.get(WorkflowDraft, id)
owner = d.owner_id
run = WorkflowRun(
owner_id=owner,
draft_id=id,
draft_revision=1,
spec_snapshot=frozen["spec"],
spec_hash="a" * 64,
run_kind="workflow_auto",
source_draft_version=2,
result_manifest=frozen,
)
s.add(run)
await s.flush()
rid = run.id
await s.commit()
changed = __import__("copy").deepcopy(frozen)
changed["spec"]["shots"][0]["prompt"] = "later edit"
response = await c.post(
f"/api/editors/{id}/save",
json={"expected_version": 2, "manifest": changed},
headers={"Idempotency-Key": "later"},
)
assert response.status_code == 200, response.text
stale = await c.post(
f"/api/editors/{id}/from-run",
json={"expected_version": 2, "run_id": rid},
headers={"Idempotency-Key": "stale"},
)
assert stale.status_code == 409
restore = await c.post(
f"/api/editors/{id}/from-run",
json={"expected_version": 3, "run_id": rid},
headers={"Idempotency-Key": "restore"},
)
assert restore.status_code == 200, restore.text
assert restore.json()["manifest"] == {**frozen, "base_run_id": rid}
async with system.app.state.db.session() as s:
refs = (
await s.scalars(
select(AssetReference).where(
AssetReference.ref_kind == "draft", AssetReference.ref_id == id
)
)
).all()
assert {x.asset_id for x in refs} == {aid}
sub = await s.scalar(select(Submission).where(Submission.operation == "editor.from_run"))
assert sub.resource_json == {"draft_id": id}
from app.services.editors import apply_run_result
run = await s.get(WorkflowRun, rid)
run.state = "succeeded"
assert not await apply_run_result(s, run, system.settings)
assert run.apply_state == "conflict"
run.state = "succeeded"
await s.commit()
archived = await c.delete(f"/api/workflow-runs/{rid}", headers={"If-Match": "1"})
assert archived.status_code == 200, archived.text
protected = await c.delete(f"/api/assets/{aid}")
assert protected.status_code == 409, protected.text
assert (await c.get(f"/api/editors/{id}")).status_code == 200
async with system.app.state.db.session() as s:
sub = await s.scalar(select(Submission).where(Submission.operation == "editor.from_run"))
assert sub.status != "purged"
async def test_editor_rejects_bearer_and_rechecks_revoked_session(system):
from app.models import Session
c = system.client
r = await c.post("/api/workflows", json={"name": "Editor", "spec": spec()})
id = r.json()["id"]
m = (await c.get(f"/api/editors/{id}")).json()["manifest"]
from app.services.editors import save_editor
from app.schemas.editors import SaveEditor
from app.core.security import Actor
from fastapi import HTTPException
async with system.app.state.db.session() as s:
row = await s.scalar(select(Session))
d = await s.get(WorkflowDraft, id)
actor = Actor(d.owner_id, "admin", "Admin", "admin", "csrf", row.token_hash)
await s.delete(row)
await s.commit()
with pytest.raises(HTTPException) as exc:
await save_editor(
system.app.state, actor, id, SaveEditor(expected_version=1, manifest=m), "revoked"
)
assert exc.value.status_code == 401
actor.auth_kind = "bearer"
with pytest.raises(HTTPException) as exc:
await save_editor(
system.app.state, actor, id, SaveEditor(expected_version=1, manifest=m), "machine"
)
assert exc.value.status_code == 403
async def test_editor_plan_run_receipt_and_legacy_guard(system):
c = system.client
r = await c.post("/api/workflows", json={"name": "Editor", "spec": spec()})
id = r.json()["id"]
m = (await c.get(f"/api/editors/{id}")).json()["manifest"]
saved = await c.post(
f"/api/editors/{id}/save",
json={"expected_version": 1, "manifest": m},
headers={"Idempotency-Key": "save"},
)
assert saved.status_code == 200, saved.text
old = await c.get(f"/api/workflows/{id}")
assert old.status_code == 200, old.text
assert old.json()["editor_manifest"] is not None
legacy = await c.patch(f"/api/workflows/{id}", json={"name": "bad"}, headers={"If-Match": "2"})
assert legacy.status_code == 409 and legacy.json()["detail"]["code"] == "editor_required"
body = {
"expected_version": 2,
"output_goal": "media",
"targets": ["frame:" + m["shot_ids"][0]],
"force": [],
"execution_mode": "interactive",
}
plan = await c.post(f"/api/editors/{id}/plan", json=body)
assert plan.status_code == 200, plan.text
body["expected_plan_hash"] = plan.json()["plan_hash"]
run = await c.post(f"/api/editors/{id}/runs", json=body, headers={"Idempotency-Key": "run"})
assert run.status_code == 202, run.text
again = await c.post(f"/api/editors/{id}/runs", json=body, headers={"Idempotency-Key": "run"})
assert again.status_code == 202, again.text
assert again.json()["run"]["id"] == run.json()["run"]["id"]
async def test_editor_imports_legacy_story_selected_frame_without_write(system, monkeypatch):
from test_story_studio import prepare_manual_frame
from app.models import ShotSelection
d, candidate, _ = await prepare_manual_frame(system, monkeypatch)
c = system.client
selected = await c.post(
f"/api/stories/{d['id']}/selections",
json={
"expected_version": 1,
"shot_id": "1" * 32,
"kind": "frame",
"candidate_id": candidate["id"],
},
headers={"Idempotency-Key": "select"},
)
assert selected.status_code == 200, selected.text
before = selected.json()["version"]
editor = await c.get(f"/api/editors/{d['id']}")
assert editor.status_code == 200, editor.text
binding = editor.json()["manifest"]["bindings"]["frame:" + ("1" * 32)]
assert binding["asset_id"] == candidate["asset"]["id"]
assert binding["source"] == "manual" and binding["locked"]
assert editor.json()["version"] == before
async with system.app.state.db.session() as s:
assert (await s.get(WorkflowDraft, d["id"])).editor_manifest is None
assert len((await s.scalars(select(ShotSelection))).all()) == 1
m = editor.json()["manifest"]
m["captions"]["cues"] = [
dict(
id="e" * 32,
anchor="shot",
shot_id="1" * 32,
start_frame=0,
end_frame=999,
text="conflict",
text_override=True,
timing_override=True,
)
]
saved = await c.post(
f"/api/editors/{d['id']}/save",
json={"expected_version": before, "manifest": m},
headers={"Idempotency-Key": "editor-save"},
)
assert saved.status_code == 200, saved.text
assert saved.json()["issues"]
assert (await c.get(f"/api/stories/{d['id']}")).status_code == 200
guarded = await c.patch(
f"/api/stories/{d['id']}", json={"name": "legacy"}, headers={"If-Match": str(before + 1)}
)
assert guarded.status_code == 409 and guarded.json()["detail"]["code"] == "editor_required"
candidate_command = await c.post(
f"/api/stories/{d['id']}/candidates",
json={"expected_version": before + 1, "shot_id": "1" * 32, "kind": "frame"},
headers={"Idempotency-Key": "legacy-candidate"},
)
assert (
candidate_command.status_code == 409
and candidate_command.json()["detail"]["code"] == "editor_required"
)
async def test_apply_requires_success_and_matching_frozen_source(system):
from app.models import WorkflowRun
c = system.client
d = (await c.post("/api/workflows", json={"name": "Editor", "spec": spec()})).json()
id = d["id"]
m = (await c.get(f"/api/editors/{id}")).json()["manifest"]
async with system.app.state.db.session() as s:
draft = await s.get(WorkflowDraft, id)
run = WorkflowRun(
owner_id=draft.owner_id,
draft_id=id,
draft_revision=1,
source_draft_version=1,
result_manifest=m,
spec_snapshot=m["spec"],
spec_hash="a" * 64,
run_kind="workflow_auto",
)
s.add(run)
await s.flush()
rid = run.id
await s.commit()
body = {"expected_version": 1, "run_id": rid}
running = await c.post(
f"/api/editors/{id}/apply", json=body, headers={"Idempotency-Key": "running"}
)
assert running.status_code == 409
async with system.app.state.db.session() as s:
(await s.get(WorkflowRun, rid)).state = "succeeded"
await s.commit()
saved = await c.post(
f"/api/editors/{id}/save",
json={"expected_version": 1, "manifest": m},
headers={"Idempotency-Key": "edited"},
)
assert saved.status_code == 200, saved.text
body["expected_version"] = 2
conflict = await c.post(
f"/api/editors/{id}/apply", json=body, headers={"Idempotency-Key": "old-result"}
)
assert conflict.status_code == 409
restored = await c.post(
f"/api/editors/{id}/from-run", json=body, headers={"Idempotency-Key": "explicit-restore"}
)
assert restored.status_code == 200, restored.text
async def test_from_run_save_start_preserves_validated_lineage_and_receipts(system):
from app.models import WorkflowRun, Submission
c = system.client
d = (await c.post("/api/workflows", json={"name": "Lineage", "spec": spec()})).json()
id = d["id"]
m = (await c.get(f"/api/editors/{id}")).json()["manifest"]
async with system.app.state.db.session() as s:
draft = await s.get(WorkflowDraft, id)
run = WorkflowRun(
owner_id=draft.owner_id,
draft_id=id,
draft_revision=1,
source_draft_version=1,
spec_snapshot=m["spec"],
spec_hash="a" * 64,
result_manifest=m,
state="succeeded",
)
s.add(run)
await s.flush()
rid = run.id
await s.commit()
restored = await c.post(
f"/api/editors/{id}/from-run",
json={"expected_version": 1, "run_id": rid},
headers={"Idempotency-Key": "restore-lineage"},
)
assert restored.status_code == 200, restored.text
assert restored.json()["manifest"]["base_run_id"] == rid
saved = await c.post(
f"/api/editors/{id}/save",
json={"expected_version": 2, "manifest": restored.json()["manifest"]},
headers={"Idempotency-Key": "save-lineage"},
)
assert saved.status_code == 200, saved.text
body = {"expected_version": 3, "output_goal": "media", "targets": ["frame:" + m["shot_ids"][0]]}
plan = await c.post(f"/api/editors/{id}/plan", json=body)
assert plan.status_code == 200, plan.text
body["expected_plan_hash"] = plan.json()["plan_hash"]
child = await c.post(
f"/api/editors/{id}/runs", json=body, headers={"Idempotency-Key": "child-lineage"}
)
assert child.status_code == 202, child.text
archived = await c.delete(f"/api/workflow-runs/{rid}", headers={"If-Match": "1"})
assert archived.status_code == 200, archived.text
async with system.app.state.db.session() as s:
child_id = child.json()["run"]["id"]
assert (await s.get(WorkflowRun, child_id)).base_run_id == rid
sub = await s.scalar(select(Submission).where(Submission.operation == "editor.run"))
assert sub.resource_json == {"draft_id": id, "run_id": child_id}
assert sub.status != "purged"
from app.services.editors import apply_run_result
child_run = await s.get(WorkflowRun, child_id)
child_run.state = "succeeded"
assert await apply_run_result(s, child_run, system.settings)
draft = await s.get(WorkflowDraft, id)
assert draft.editor_manifest["base_run_id"] == child_id
assert child_run.result_manifest["base_run_id"] == child_id
assert child_run.plan_snapshot["manifest"]["base_run_id"] == rid
assert child_run.base_run_id == rid
await s.commit()
archived_source = await c.post(
f"/api/editors/{id}/save",
json={"expected_version": 4, "manifest": restored.json()["manifest"]},
headers={"Idempotency-Key": "archived-source"},
)
assert archived_source.status_code == 200, archived_source.text
# 别的同owner草稿不允许借用来源ID,也不允许通过save扩大来源读取。
other = (await c.post("/api/workflows", json={"name": "Other", "spec": spec()})).json()
other_m = (await c.get(f"/api/editors/{other['id']}")).json()["manifest"]
other_m["base_run_id"] = rid
forged = await c.post(
f"/api/editors/{other['id']}/save",
json={"expected_version": 1, "manifest": other_m},
headers={"Idempotency-Key": "forged-lineage"},
)
assert forged.status_code == 404, forged.text
async def test_manual_audio_binding_uses_server_duration_and_preserves_trusted_samples(system):
from app.models import Asset
c = system.client
d = (await c.post("/api/workflows", json={"name": "Audio facts", "spec": spec()})).json()
id = d["id"]
m = (await c.get(f"/api/editors/{id}")).json()["manifest"]
segment = m["audio"]["segments"][0]["id"]
async with system.app.state.db.session() as s:
draft = await s.get(WorkflowDraft, id)
a = Asset(
owner_id=draft.owner_id,
name="duration.wav",
storage_key="test/duration.wav",
kind="audio",
mime_type="audio/wav",
size_bytes=1,
sha256="a" * 64,
ready=True,
duration_seconds=0.0501,
)
s.add(a)
await s.flush()
aid = a.id
await s.commit()
key = "audio:" + segment
m["bindings"][key] = dict(
asset_id=aid,
kind="audio",
source="manual",
sample_count=1,
duration_frames=900,
duration_seconds=900.0,
)
saved = await c.post(
f"/api/editors/{id}/save",
json={"expected_version": 1, "manifest": m},
headers={"Idempotency-Key": "audio-facts"},
)
assert saved.status_code == 200, saved.text
binding = saved.json()["manifest"]["bindings"][key]
assert binding["duration_seconds"] == 0.0501 and binding["duration_frames"] == 2
assert binding.get("sample_count") is None
async with system.app.state.db.session() as s:
draft = await s.get(WorkflowDraft, id)
trusted = __import__("copy").deepcopy(draft.editor_manifest)
trusted["bindings"][key]["sample_count"] = 2405
draft.editor_manifest = trusted
await s.commit()
changed = saved.json()["manifest"]
changed["bindings"][key]["sample_count"] = 1
saved = await c.post(
f"/api/editors/{id}/save",
json={"expected_version": 2, "manifest": changed},
headers={"Idempotency-Key": "trusted-facts"},
)
assert saved.status_code == 200, saved.text
assert saved.json()["manifest"]["bindings"][key]["sample_count"] == 2405