cmvr-visual/backend/tests/test_story_asset_cleanup.py

160 lines
6.5 KiB
Python

from pathlib import Path
from sqlalchemy import select
from app.models import Asset, Event, Job, ShotCandidate, WorkflowDraft, new_id, utcnow
from test_asset_physical_deletion import files_for, upload
from test_story_studio import story_spec
async def story_with_refs(system, ids):
spec = story_spec()
spec["scenes"] = [{"id": "a" * 32, "name": "修鞋铺", "reference_asset_ids": list(ids)}]
response = await system.client.post(
"/api/stories", json={"name": "归属验证", "spec": spec, "create_folder": False}
)
assert response.status_code == 201, response.text
return response.json()
async def test_delete_story_removes_exclusive_assets_and_keeps_favorites_and_other_uses(
system, png_bytes
):
assets = [await upload(system, png_bytes) for _ in range(6)]
exclusive, favorite, shared, standalone, job_input, foreign_output = [a["id"] for a in assets]
story = await story_with_refs(system, [exclusive, favorite, shared, job_input, foreign_output])
await story_with_refs(system, [shared])
saved = await system.client.patch(f"/api/assets/{favorite}", json={"favorite": True})
assert saved.status_code == 200
job = await system.client.post(
"/api/jobs",
json={
"task_type": "defect.generate",
"input": {"prompt": "线", "image_asset_id": job_input},
},
)
assert job.status_code == 202, job.text
async with system.app.state.db.session() as session:
producer = await session.get(Job, job.json()["jobs"][0]["id"])
producer.state = "succeeded"
(await session.get(Asset, foreign_output)).source_job_id = producer.id
await session.commit()
paths = await files_for(system, exclusive)
assert paths and all(p.is_file() for p in paths)
response = await system.client.delete(
f"/api/stories/{story['id']}", headers={"If-Match": str(story["version"])}
)
assert response.status_code == 200, response.text
assert (await system.client.get(f"/api/assets/{exclusive}/content")).status_code == 404
assert all(not p.exists() for p in paths)
assert response.json()["deleted"]["asset_ids"] == [exclusive]
for aid in (favorite, shared, standalone, job_input, foreign_output):
assert (await system.client.get(f"/api/assets/{aid}/content")).status_code == 200
async with system.app.state.db.session() as session:
assert (await session.get(WorkflowDraft, story["id"])).deleted_at is not None
events = await session.scalars(select(Event).where(Event.event_type == "asset.deleted"))
assert [event.data["id"] for event in events] == [exclusive]
async def test_story_cleanup_finds_older_job_outputs_and_keeps_favorited_normalized_copy(
system, png_bytes
):
from test_story_deletion_sort_memory import history
story = await history(system)
source = (await upload(system, png_bytes))["id"]
async with system.app.state.db.session() as session:
row = await session.get(Asset, source)
row.kind, row.origin, row.source_job_id = "video", "generated", "f" * 32
caches = {}
for favorite in (False, True):
cache_id = new_id()
key = f"{row.owner_id}/{cache_id}/{source}.mp4"
path = system.settings.asset_root / key
path.parent.mkdir(parents=True)
path.write_bytes(b"cached bytes")
session.add(
Asset(
id=cache_id,
owner_id=row.owner_id,
name="片段缓存",
storage_key=key,
kind="video",
origin="normalized",
mime_type="video/mp4",
sha256="a" * 64,
size_bytes=12,
favorite=favorite,
)
)
caches[favorite] = (cache_id, path)
await session.commit()
response = await system.client.delete(
f"/api/stories/{story['id']}", headers={"If-Match": str(story["version"])}
)
assert response.status_code == 200, response.text
assert set(response.json()["deleted"]["asset_ids"]) == {source, caches[False][0]}
assert not caches[False][1].exists()
assert caches[True][1].is_file()
async def test_archived_manual_candidate_keeps_asset_provenance(system, png_bytes):
story = await story_with_refs(system, [])
aid = (await upload(system, png_bytes))["id"]
async with system.app.state.db.session() as session:
draft = await session.get(WorkflowDraft, story["id"])
session.add(
ShotCandidate(
owner_id=draft.owner_id,
draft_id=draft.id,
shot_id="1" * 32,
kind="video",
source_kind="manual",
asset_id=aid,
context_hash="0" * 64,
generation_hash="1" * 64,
created_revision=1,
state="succeeded",
deleted_at=utcnow(),
)
)
await session.commit()
response = await system.client.delete(
f"/api/stories/{story['id']}", headers={"If-Match": str(story["version"])}
)
assert response.status_code == 200
assert response.json()["deleted"]["asset_ids"] == [aid]
async def test_file_failure_hides_assets_before_unlink_and_resumes_cleanup(
system, png_bytes, monkeypatch
):
aid = (await upload(system, png_bytes))["id"]
story = await story_with_refs(system, [aid])
original, thumbnail = await files_for(system, aid)
unlink = Path.unlink
def fail_on_thumbnail(path, *args, **kwargs):
if path == thumbnail:
raise PermissionError("thumbnail locked")
return unlink(path, *args, **kwargs)
url = f"/api/stories/{story['id']}"
headers = {"If-Match": str(story["version"])}
with monkeypatch.context() as patch:
patch.setattr(Path, "unlink", fail_on_thumbnail)
response = await system.client.delete(url, headers=headers)
assert response.status_code == 202
assert not original.exists() and thumbnail.is_file()
assert (await system.client.get(f"/api/assets/{aid}")).status_code == 404
assert (
await system.client.patch(f"/api/assets/{aid}", json={"favorite": True})
).status_code == 404
from app.services.stories.deletion import resume_story_deletions
await resume_story_deletions(system.app.state)
assert not thumbnail.exists()
result = await system.client.delete(url, headers=headers)
assert result.status_code == 200 and result.json()["deleted"]["asset_ids"] == [aid]