cmvr-visual/backend/tests/test_folder_propagation.py

744 lines
29 KiB
Python
Raw Normal View History

import pytest
async def folder(client, name):
r = await client.post("/api/folders", json={"name": name})
assert r.status_code == 201, r.text
return r.json()["id"]
@pytest.mark.asyncio
async def test_upload_patch_filter_and_foreign_folder(system, other_client, png_bytes):
c = system.client
fid = await folder(c, "素材")
foreign = await folder(other_client, "私有")
rejected = await c.post(
"/api/assets",
data={"folder_id": foreign},
files={"file": ("x.png", png_bytes, "image/png")},
)
assert rejected.status_code == 404
r = await c.post(
"/api/assets", data={"folder_id": fid}, files={"file": ("x.png", png_bytes, "image/png")}
)
assert r.status_code == 201, r.text
asset = r.json()
assert asset["folder_ids"] == [fid]
assert (await c.get("/api/assets", params={"folder_id": "unclassified"})).json()["total"] == 0
patched = await c.patch("/api/assets/" + asset["id"], json={"folder_ids": []})
assert patched.status_code == 200, patched.text
assert patched.json()["folder_ids"] == []
assert (await c.get("/api/assets", params={"folder_id": fid})).json()["total"] == 0
assert (await c.get("/api/assets", params={"folder_id": foreign})).status_code == 404
@pytest.mark.asyncio
async def test_job_targets_idempotency_retry_and_deleted_target(system):
from app.models import Job
from app.services.assets import import_output
from PIL import Image
c = system.client
fid = await folder(c, "生成")
body = {"task_type": "image.generate", "input": {"prompt": "tree"}, "folder_id": fid}
r = await c.post("/api/jobs", json=body, headers={"Idempotency-Key": "folder-job"})
assert r.status_code == 202, r.text
job = r.json()["jobs"][0]
assert job["folder_id"] == job["output_folder_id"] == fid
assert (await c.post("/api/jobs", json=body, headers={"Idempotency-Key": "folder-job"})).json()[
"jobs"
][0]["id"] == job["id"]
assert (
await c.post(
"/api/jobs",
json={**body, "output_folder_id": None},
headers={"Idempotency-Key": "folder-job"},
)
).status_code == 409
async with system.app.state.db.session() as s:
row = await s.get(Job, job["id"])
row.state = "failed"
await s.commit()
retry = await c.post("/api/jobs/" + job["id"] + "/retry")
assert retry.status_code == 202, retry.text
assert retry.json()["jobs"][0]["output_folder_id"] == fid
assert (await c.delete("/api/folders/" + fid)).status_code == 204
source = system.settings.job_work_root / "result.png"
source.parent.mkdir(parents=True, exist_ok=True)
Image.new("RGB", (12, 12)).save(source)
asset = await import_output(system.app.state.db, system.settings, row, source, 0)
assert (
await c.get("/api/assets/" + asset.id)
).status_code == 404 # publication remains coordinator-owned
async with system.app.state.db.session() as s:
from app.models import Asset
saved = await s.get(Asset, asset.id)
assert not saved.folder_links
@pytest.mark.asyncio
async def test_story_default_folder_and_explicit_null(system):
from test_story_studio import story_spec
c = system.client
first = await c.post("/api/stories", json={"name": "故事", "spec": story_spec()})
assert first.status_code == 201, first.text
assert first.json()["folder_id"]
second = await c.post("/api/stories", json={"name": "故事", "spec": story_spec()})
assert second.json()["folder_id"] != first.json()["folder_id"]
unc = await c.post(
"/api/stories", json={"name": "未分类", "spec": story_spec(), "folder_id": None}
)
assert unc.status_code == 201, unc.text
assert unc.json()["folder_id"] is None
assert (await c.get("/api/stories", params={"folder_id": "unclassified"})).json()["total"] == 1
@pytest.mark.asyncio
async def test_workflow_frozen_target_children(system):
from test_timeline_v2 import spec
from app.services.orchestration.workflow_engine import advance_workflows
c = system.client
fid = await folder(c, "workflow")
response = await c.post("/api/workflows", json={"name": "w", "spec": spec(), "folder_id": fid})
assert response.status_code == 201, response.text
d = response.json()
body = {"draft_revision": d["revision"], "expected_version": d["version"]}
started = await c.post(
"/api/workflows/" + d["id"] + "/runs", json=body, headers={"Idempotency-Key": "freeze"}
)
assert started.status_code == 202, started.text
run = started.json()["run"]
assert run["output_folder_id"] == fid
current = (await c.get("/api/workflows/" + d["id"])).json()
assert (
await c.patch(
"/api/workflows/" + d["id"],
json={"folder_id": None},
headers={"If-Match": str(current["version"])},
)
).status_code == 200
await advance_workflows(system.app.state.db, system.settings, system.provider)
snap = (await c.get("/api/workflow-runs/" + run["id"])).json()
assert snap["jobs"] and all(j["output_folder_id"] == fid for j in snap["jobs"])
@pytest.mark.asyncio
async def test_queued_candidate_freezes_target(system):
from test_story_studio import story_spec
from app.models import ShotCandidate, Job
from sqlalchemy import select
from app.services.stories.candidates import feed_candidates
c = system.client
d = (await c.post("/api/stories", json={"name": "candidate", "spec": story_spec()})).json()
assert d.get("folder_id")
body = {"expected_version": d["version"], "shot_id": "1" * 32, "kind": "frame"}
r = await c.post(
"/api/stories/" + d["id"] + "/candidates",
json=body,
headers={"Idempotency-Key": "candidate-freeze"},
)
assert r.status_code == 202, r.text
current = (await c.get("/api/stories/" + d["id"])).json()
assert (
await c.patch(
"/api/stories/" + d["id"],
json={"folder_id": None},
headers={"If-Match": str(current["version"])},
)
).status_code == 200
async with system.app.state.db.session() as s:
candidate = await s.scalar(select(ShotCandidate).where(ShotCandidate.draft_id == d["id"]))
assert candidate.plan_json["output_folder_id"] == d["folder_id"]
await feed_candidates(s, system.settings)
await s.commit()
j = await s.get(Job, candidate.job_id)
assert j.output_folder_id == d["folder_id"]
@pytest.mark.asyncio
async def test_queued_candidate_deleted_target_falls_back(system):
from test_story_studio import story_spec
from app.models import ShotCandidate, Job
from app.services.stories.candidates import feed_candidates
from sqlalchemy import select
c = system.client
d = (await c.post("/api/stories", json={"name": "deleted", "spec": story_spec()})).json()
r = await c.post(
"/api/stories/" + d["id"] + "/candidates",
json={"expected_version": 1, "shot_id": "1" * 32, "kind": "frame"},
headers={"Idempotency-Key": "deleted-candidate"},
)
assert r.status_code == 202, r.text
assert (await c.delete("/api/folders/" + d["folder_id"])).status_code == 204
async with system.app.state.db.session() as s:
await feed_candidates(s, system.settings)
candidate = await s.scalar(select(ShotCandidate).where(ShotCandidate.draft_id == d["id"]))
assert candidate.job_id, candidate.error_json
assert (await s.get(Job, candidate.job_id)).output_folder_id is None
@pytest.mark.asyncio
async def test_old_job_hash_and_submission_body_remain_compatible(system):
import hashlib
import json
from app.models import Job, Submission
from app.services.submissions import body_hash
from sqlalchemy import select
c = system.client
body = {"task_type": "image.generate", "input": {"prompt": "old"}}
response = await c.post("/api/jobs", json=body, headers={"Idempotency-Key": "old-hash"})
assert response.status_code == 202, response.text
legacy = {**body, "parameters": {}, "count": 1, "scheduled_at": None}
expected = hashlib.sha256(
json.dumps(legacy, sort_keys=True, ensure_ascii=False, allow_nan=False).encode()
).hexdigest()
async with system.app.state.db.session() as s:
j = await s.get(Job, response.json()["jobs"][0]["id"])
sub = await s.scalar(select(Submission).where(Submission.key == "old-hash"))
assert j.request_hash == expected
assert sub.body_hash == body_hash({**legacy, "execution_mode": "interactive"}, 2)
@pytest.mark.asyncio
async def test_shared_import_target_and_old_no_body(system, png_bytes, other_client):
c = system.client
asset = (await c.post("/api/assets", files={"file": ("x.png", png_bytes, "image/png")})).json()
pub = await c.post(
"/api/assets/" + asset["id"] + "/publish", headers={"Idempotency-Key": "publish-folder"}
)
assert pub.status_code == 201, pub.text
shared_id = pub.json()["id"]
foreign = await folder(other_client, "foreign-import")
before_files = set(system.settings.asset_root.rglob("*"))
denied = await c.post(
"/api/shared-assets/" + shared_id + "/import",
json={"folder_id": foreign},
headers={"Idempotency-Key": "foreign-import"},
)
assert denied.status_code == 404, denied.text
assert set(system.settings.asset_root.rglob("*")) == before_files
fid = await folder(c, "import")
first = await c.post(
"/api/shared-assets/" + shared_id + "/import",
json={"folder_id": fid},
headers={"Idempotency-Key": "import-folder"},
)
assert first.status_code == 201, first.text
assert first.json()["folder_ids"] == [fid]
assert (
await c.post(
"/api/shared-assets/" + shared_id + "/import",
json={},
headers={"Idempotency-Key": "import-folder"},
)
).status_code == 409
old = await c.post("/api/shared-assets/" + shared_id + "/import")
assert old.status_code == 201, old.text
assert old.json()["folder_ids"] == []
assert (await c.delete("/api/folders/" + fid)).status_code == 204
replay = await c.post(
"/api/shared-assets/" + shared_id + "/import",
json={"folder_id": fid},
headers={"Idempotency-Key": "import-folder"},
)
assert replay.status_code == 201, replay.text
assert replay.json()["id"] == first.json()["id"]
assert replay.json()["folder_ids"] == []
assert (
await c.post(
"/api/shared-assets/" + shared_id + "/import",
json={},
headers={"Idempotency-Key": "import-folder"},
)
).status_code == 409
@pytest.mark.asyncio
async def test_batch_job_and_workflow_targets(system):
from test_timeline_v2 import spec
c = system.client
fid = await folder(c, "batch")
d = (
await c.post("/api/workflows", json={"name": "w", "spec": spec(), "folder_id": fid})
).json()
items = [
{
"kind": "job",
"task_type": "image.generate",
"input": {"prompt": "tree"},
"folder_id": fid,
"output_folder_id": None,
},
{
"kind": "workflow",
"draft_id": d["id"],
"draft_revision": d["revision"],
"expected_version": d["version"],
"output_folder_id": None,
},
]
response = await c.post(
"/api/batches", json={"items": items}, headers={"Idempotency-Key": "folder-batch"}
)
assert response.status_code == 202, response.text
from app.models import Job, WorkflowRun
async with system.app.state.db.session() as s:
records = response.json()["items"]
job = await s.get(Job, records[0]["target_id"])
run = await s.get(WorkflowRun, records[1]["target_id"])
assert job.folder_id == run.folder_id == fid
assert job.output_folder_id is run.output_folder_id is None
@pytest.mark.asyncio
async def test_manual_source_keeps_membership_and_output_freezes(system, monkeypatch, png_bytes):
import asyncio
from app.adapters.provider.client import Provider
from test_story_studio import story_spec
c = system.client
source_folder = await folder(c, "source")
d = (await c.post("/api/stories", json={"name": "manual", "spec": story_spec()})).json()
source = (
await c.post(
"/api/assets",
data={"folder_id": source_folder},
files={"file": ("x.png", png_bytes, "image/png")},
)
).json()
response = await c.post(
"/api/stories/" + d["id"] + "/candidates",
json={
"expected_version": 1,
"shot_id": "1" * 32,
"kind": "frame",
"source_kind": "manual",
"asset_id": source["id"],
},
headers={"Idempotency-Key": "manual-folder"},
)
assert response.status_code == 202, response.text
assert set((await c.get("/api/assets/" + source["id"])).json()["folder_ids"]) == {
source_folder,
d["folder_id"],
}
target = await folder(c, "later")
assert (
await c.patch(
"/api/stories/" + d["id"], json={"folder_id": target}, headers={"If-Match": "1"}
)
).status_code == 200
real = Provider(system.settings)
monkeypatch.setattr(system.provider, "run_cpu", real.run_cpu)
try:
for _ in range(4):
await system.app.state.coordinator.run_once()
tasks = list(system.app.state.coordinator._cpu.values())
if tasks:
await asyncio.gather(*tasks)
candidate = (await c.get("/api/stories/" + d["id"] + "/candidates")).json()["items"][0]
assert candidate["state"] == "ready", candidate
assert candidate["asset"]["folder_ids"] == [d["folder_id"]]
moved = await c.patch("/api/assets/" + candidate["asset"]["id"], json={"folder_ids": []})
assert moved.status_code == 200
assert (await c.delete("/api/assets/" + candidate["asset"]["id"])).status_code == 409
finally:
await real.aclose()
@pytest.mark.asyncio
async def test_candidate_targets_do_not_change_generation_hash_and_old_plan_unclassified(system):
from test_story_studio import story_spec
from app.models import ShotCandidate, Job
from app.services.stories.candidates import feed_candidates
c = system.client
d = (await c.post("/api/stories", json={"name": "hash", "spec": story_spec()})).json()
body = {"expected_version": 1, "shot_id": "1" * 32, "kind": "frame"}
first = await c.post(
"/api/stories/" + d["id"] + "/candidates",
json=body,
headers={"Idempotency-Key": "hash-first"},
)
second = await c.post(
"/api/stories/" + d["id"] + "/candidates",
json={**body, "output_folder_id": None},
headers={"Idempotency-Key": "hash-second"},
)
assert first.status_code == second.status_code == 202
a, b = first.json()["candidates"][0], second.json()["candidates"][0]
assert a["generation_hash"] == b["generation_hash"]
assert (
await c.post(
"/api/stories/" + d["id"] + "/candidates",
json={**body, "output_folder_id": None},
headers={"Idempotency-Key": "hash-first"},
)
).status_code == 409
async with system.app.state.db.session() as s:
old = await s.get(ShotCandidate, a["id"])
old.plan_json = {
k: v for k, v in old.plan_json.items() if k not in {"folder_id", "output_folder_id"}
}
await feed_candidates(s, system.settings)
job = await s.get(Job, old.job_id)
assert job.folder_id is job.output_folder_id is None
@pytest.mark.asyncio
async def test_workflow_retry_reuse_and_final_output_keep_target(system):
from test_timeline_v2 import spec
from test_workflows_v2 import publish_video
from app.services.orchestration.workflow_engine import advance_workflows
from app.models import Job
from app.services.events import event_batch
c = system.client
fid = await folder(c, "reuse-one")
target = await folder(c, "reuse-two")
d = (
await c.post("/api/workflows", json={"name": "reuse", "spec": spec(), "folder_id": fid})
).json()
first = await c.post(
"/api/workflows/" + d["id"] + "/runs",
json={"draft_revision": 1, "expected_version": 1},
headers={"Idempotency-Key": "reuse-first"},
)
rid = first.json()["run"]["id"]
await advance_workflows(system.app.state.db, system.settings, system.provider)
snap = (await c.get("/api/workflow-runs/" + rid)).json()
old = next(x for x in snap["steps"] if x["step_key"] == "shot_1")["selected_job_id"]
async with system.app.state.db.session() as s:
j = await s.get(Job, old)
j.state = j.phase = "failed"
await s.commit()
await advance_workflows(system.app.state.db, system.settings, system.provider)
snap = (await c.get("/api/workflow-runs/" + rid)).json()
retry = await c.post(
"/api/workflow-runs/" + rid + "/steps/shot_1/retry",
json={"expected_run_version": snap["run"]["version"], "target_job_id": old},
headers={"Idempotency-Key": "reuse-retry"},
)
assert retry.status_code == 202, retry.text
replacement = next(
x for x in retry.json()["jobs"] if x["id"] != old and x["step_key"] == "shot_1"
)
assert replacement["output_folder_id"] == fid
outputs = []
for step in retry.json()["steps"]:
if step["step_key"] != "compose":
outputs.append(await publish_video(system, step["selected_job_id"]))
await advance_workflows(system.app.state.db, system.settings, system.provider)
snap = (await c.get("/api/workflow-runs/" + rid)).json()
compose = next(x for x in snap["jobs"] if x["step_key"] == "compose")
assert compose["output_folder_id"] == fid
await publish_video(system, compose["id"], compose=True)
await advance_workflows(system.app.state.db, system.settings, system.provider)
current = (await c.get("/api/workflows/" + d["id"])).json()
owner = (await c.get("/api/auth/me")).json()["user"]["id"]
cursor = (await event_batch(system.app.state.db, owner, 0, limit=1000))[-1]["id"]
reused = await c.post(
"/api/workflows/" + d["id"] + "/runs",
json={
"draft_revision": current["revision"],
"expected_version": current["version"],
"reuse_run_id": rid,
"output_folder_id": target,
},
headers={"Idempotency-Key": "reuse-second"},
)
assert reused.status_code == 202, reused.text
assert len([x for x in reused.json()["steps"] if x["state"] == "succeeded"]) == 3
for aid in outputs:
assert target in (await c.get("/api/assets/" + aid)).json()["folder_ids"]
events = await event_batch(system.app.state.db, owner, cursor)
updated = [e["data"]["asset"] for e in events if e["event"] == "asset.updated"]
assert {a["id"] for a in updated} == set(outputs)
assert len(updated) == len(outputs)
assert all(target in a["folder_ids"] for a in updated)
cursor = events[-1]["id"]
current = (await c.get("/api/workflows/" + d["id"])).json()
unchanged = await c.post(
"/api/workflows/" + d["id"] + "/runs",
json={
"draft_revision": current["revision"],
"expected_version": current["version"],
"reuse_run_id": rid,
"output_folder_id": target,
"execution_mode": "batch",
},
headers={"Idempotency-Key": "reuse-same-folder"},
)
assert unchanged.status_code == 202, unchanged.text
assert not [
e
for e in await event_batch(system.app.state.db, owner, cursor)
if e["event"] == "asset.updated"
]
@pytest.mark.asyncio
async def test_generated_output_archived_and_metadata_never_sent_upstream(system):
c = system.client
fid = await folder(c, "generated")
response = await c.post(
"/api/jobs",
json={"task_type": "image.generate", "input": {"prompt": "tree"}, "folder_id": fid},
)
assert response.status_code == 202, response.text
job = response.json()["jobs"][0]
for _ in range(4):
await system.app.state.coordinator.run_once(force=True)
if system.provider.remote:
break
assert system.provider.remote
payload = system.provider.submitted_payloads[0][1]
assert "folder_id" not in payload and "output_folder_id" not in payload
assert "folder_id" not in payload["parameters"]
next(iter(system.provider.remote.values())).update(
state="succeeded", result={"outputs": [{"path": "out.png"}]}
)
for _ in range(4):
await system.app.state.coordinator.run_once(force=True)
current = (await c.get("/api/jobs/" + job["id"])).json()
assert current["state"] == "succeeded", current
assert current["result_assets"][0]["folder_ids"] == [fid]
@pytest.mark.asyncio
@pytest.mark.parametrize("destination", ["inherit", "explicit", "unclassified"])
async def test_story_render_real_compose_freezes_output(system, monkeypatch, destination):
import asyncio
import shutil
from app.adapters.media import run_process
from app.adapters.provider.client import Provider
from test_story_studio import story_spec
if not shutil.which("ffmpeg") or not shutil.which("ffprobe"):
pytest.skip("FFmpeg required")
c = system.client
spec = story_spec()
spec["shots"][0]["edit"] = {"start_frame": 0, "duration_frames": 24}
spec["render"] = {"total_frames": 24}
d = (await c.post("/api/stories", json={"name": "render", "spec": spec})).json()
target = (
await folder(c, "render-target")
if destination == "explicit"
else d["folder_id"]
if destination == "inherit"
else None
)
video = system.settings.workspace_root / "folder-video.mp4"
await run_process(
[
system.settings.ffmpeg_bin,
"-v",
"error",
"-f",
"lavfi",
"-i",
"color=c=blue:s=256x256:r=24",
"-frames:v",
"24",
"-c:v",
"libx264",
"-pix_fmt",
"yuv420p",
str(video),
]
)
source = await c.post(
"/api/assets", files={"file": ("video.mp4", video.read_bytes(), "video/mp4")}
)
assert source.status_code == 201, source.text
base = "/api/stories/" + d["id"]
candidate = await c.post(
base + "/candidates",
json={
"expected_version": 1,
"shot_id": "1" * 32,
"kind": "video",
"source_kind": "manual",
"asset_id": source.json()["id"],
},
headers={"Idempotency-Key": "render-video"},
)
assert candidate.status_code == 202, candidate.text
selected = await c.post(
base + "/selections",
json={
"expected_version": 1,
"shot_id": "1" * 32,
"kind": "video",
"candidate_id": candidate.json()["candidates"][0]["id"],
},
headers={"Idempotency-Key": "render-select"},
)
assert selected.status_code == 200, selected.text
body = {"expected_version": selected.json()["version"]}
if destination != "inherit":
body["output_folder_id"] = target
rendered = await c.post(
base + "/renders", json=body, headers={"Idempotency-Key": "render-freeze"}
)
assert rendered.status_code == 202, rendered.text
run = rendered.json()["run"]
assert run["output_folder_id"] == target
current = (await c.get(base)).json()
assert (
await c.patch(base, json={"folder_id": None}, headers={"If-Match": str(current["version"])})
).status_code == 200
real = Provider(system.settings)
monkeypatch.setattr(system.provider, "run_cpu", real.run_cpu)
try:
for _ in range(5):
await system.app.state.coordinator.run_once()
tasks = list(system.app.state.coordinator._cpu.values())
if tasks:
await asyncio.gather(*tasks)
snap = (await c.get("/api/workflow-runs/" + run["id"])).json()
assert snap["run"]["state"] == "succeeded", snap
assert snap["run"]["result_assets"][0]["folder_ids"] == ([target] if target else [])
finally:
await real.aclose()
@pytest.mark.asyncio
async def test_foreign_folder_rejected_by_submit_drafts_candidates_and_lists(system, other_client):
from test_story_studio import story_spec
from test_timeline_v2 import spec
c = system.client
foreign = await folder(other_client, "foreign")
assert (
await c.post(
"/api/jobs",
json={
"task_type": "image.generate",
"input": {"prompt": "tree"},
"output_folder_id": foreign,
},
)
).status_code == 404
assert (
await c.post(
"/api/stories", json={"name": "foreign", "spec": story_spec(), "folder_id": foreign}
)
).status_code == 404
assert (
await c.post(
"/api/workflows", json={"name": "foreign", "spec": spec(), "folder_id": foreign}
)
).status_code == 404
d = (await c.post("/api/stories", json={"name": "own", "spec": story_spec()})).json()
assert (
await c.post(
"/api/stories/" + d["id"] + "/candidates",
json={
"expected_version": 1,
"shot_id": "1" * 32,
"kind": "frame",
"output_folder_id": foreign,
},
headers={"Idempotency-Key": "foreign-output"},
)
).status_code == 404
for endpoint in ("assets", "jobs", "stories", "workflows", "workflow-runs"):
assert (await c.get("/api/" + endpoint, params={"folder_id": foreign})).status_code == 404
assert not system.provider.submitted_payloads
@pytest.mark.asyncio
async def test_gpu_preparation_may_span_ticks_without_losing_folder_target(system, monkeypatch):
import asyncio
c = system.client
target = await folder(c, "slow-prepare")
response = await c.post(
"/api/jobs",
json={"task_type": "image.generate", "input": {"prompt": "tree"}, "folder_id": target},
)
assert response.status_code == 202, response.text
original = system.provider.prepare_gpu_payload
gate = asyncio.Event()
async def delayed_prepare(*args, **kwargs):
await gate.wait()
return await original(*args, **kwargs)
monkeypatch.setattr(system.provider, "prepare_gpu_payload", delayed_prepare)
await system.app.state.coordinator.run_once(force=True)
assert not system.provider.remote
pending = list(system.app.state.coordinator._preparing.values())
assert pending and any(not task.done() for task in pending)
gate.set()
await asyncio.wait_for(asyncio.gather(*pending), timeout=5)
await system.app.state.coordinator.run_once(force=True)
assert system.provider.remote
current = (await c.get("/api/jobs/" + response.json()["jobs"][0]["id"])).json()
assert current["output_folder_id"] == target
@pytest.mark.asyncio
@pytest.mark.parametrize("entry", ["reference", "manual"])
async def test_story_membership_change_emits_asset_update_once(system, png_bytes, entry):
from test_story_studio import story_spec
from app.services.events import event_batch
c = system.client
owner = (await c.get("/api/auth/me")).json()["user"]["id"]
original = await folder(c, "original")
target = await folder(c, "story-member")
source = (
await c.post(
"/api/assets",
data={"folder_id": original},
files={"file": ("x.png", png_bytes, "image/png")},
)
).json()
spec = story_spec()
if entry == "reference":
spec["entities"] = [
{"id": "2" * 32, "name": "Person", "reference_asset_ids": [source["id"]]}
]
spec["shots"][0]["cast"] = [{"id": "3" * 32, "entity_id": "2" * 32}]
else:
story = (
await c.post("/api/stories", json={"name": "manual", "folder_id": target, "spec": spec})
).json()
cursor = (await event_batch(system.app.state.db, owner, 0))[-1]["id"]
for index in range(2):
if entry == "reference":
response = await c.post(
"/api/stories", json={"name": "reference", "folder_id": target, "spec": spec}
)
assert response.status_code == 201, response.text
else:
response = await c.post(
"/api/stories/" + story["id"] + "/candidates",
json={
"expected_version": 1,
"shot_id": "1" * 32,
"kind": "frame",
"source_kind": "manual",
"asset_id": source["id"],
},
headers={"Idempotency-Key": "member-" + str(index)},
)
assert response.status_code == 202, response.text
events = await event_batch(system.app.state.db, owner, cursor)
updates = [e["data"]["asset"] for e in events if e["event"] == "asset.updated"]
assert len(updates) == (1 if index == 0 else 0), events
if updates:
assert updates[0]["id"] == source["id"]
assert set(updates[0]["folder_ids"]) == {original, target}
cursor = events[-1]["id"]