cmvr-visual/backend/tests/test_asset_physical_deletion.py
zhanghao 88cf14d794 feat: consolidate story studio and editable automatic production
Restructure backend and frontend modules; add story, library, and editor schema migrations.

Support editable automatic production, manual confirmation modes, account and user lifecycle management, compact container scrolling, consistent forms, and per-task result previews.

Update inference and TTS scheduling, deployment guidance, and regression coverage; remove obsolete standalone pages and temporary acceptance artifacts.
2026-11-14 14:07:26 +08:00

266 lines
12 KiB
Python

"""Deletion removes owned bytes and links without damaging independent copies."""
import os
from pathlib import Path
import pytest
from sqlalchemy import select
from app.models import Asset, Job, JobAsset
from app.models import AssetReference, AssetTag, Execution, SharedAsset
async def upload(system, png_bytes, client=None):
result = await (client or system.client).post(
"/api/assets", files={"file": ("reference.png", png_bytes, "image/png")}
)
assert result.status_code == 201, result.text
return result.json()
async def files_for(system, asset_id):
async with system.app.state.db.session() as session:
asset = await session.get(Asset, asset_id)
return [
system.settings.asset_root / key
for key in (asset.storage_key, asset.thumbnail_key)
if key
]
async def test_private_delete_removes_files_and_all_asset_links(system, png_bytes):
asset = await upload(system, png_bytes)
await system.client.patch(f"/api/assets/{asset['id']}", json={"tags": ["reference"]})
job = (
await system.client.post(
"/api/jobs",
json={
"task_type": "defect.generate",
"input": {"prompt": "scratch", "image_asset_id": asset["id"]},
},
)
).json()["jobs"][0]
async with system.app.state.db.session() as session:
(await session.get(Job, job["id"])).state = "failed"
row = await session.get(Asset, asset["id"])
session.add(
AssetReference(
owner_id=row.owner_id, asset_id=row.id, ref_kind="execution", ref_id="finished"
)
)
await session.commit()
files = await files_for(system, asset["id"])
assert len(files) == 2 and all(path.is_file() for path in files)
response = await system.client.delete(f"/api/assets/{asset['id']}")
assert response.status_code == 204, response.text
assert all(not path.exists() for path in files)
async with system.app.state.db.session() as session:
assert await session.get(Asset, asset["id"]) is None
for model in (JobAsset, AssetReference, AssetTag):
assert await session.scalar(select(model).where(model.asset_id == asset["id"])) is None
assert (await system.client.get("/api/assets")).json()["total"] == 0
for url in (
f"/api/assets/{asset['id']}",
asset["preview_url"],
asset["thumbnail_url"],
asset["download_url"],
):
assert (await system.client.get(url)).status_code == 404
assert (await system.client.delete(f"/api/assets/{asset['id']}")).status_code == 404
async def test_source_and_publication_deletion_preserve_each_import(
system, other_client, png_bytes
):
source = await upload(system, png_bytes)
shared = (await system.client.post(f"/api/assets/{source['id']}/publish")).json()
imports = []
for client in (system.client, other_client):
response = await client.post(f"/api/shared-assets/{shared['id']}/import")
assert response.status_code == 201, response.text
imports.append((client, response.json()))
async with system.app.state.db.session() as session:
snapshot_id = (await session.get(SharedAsset, shared["id"])).asset_id
source_files = await files_for(system, source["id"])
snapshot_files = await files_for(system, snapshot_id)
imported_files = [await files_for(system, asset["id"]) for _, asset in imports]
originals = [source_files[0], snapshot_files[0], *(paths[0] for paths in imported_files)]
assert len({path.stat().st_ino for path in originals}) == 4
assert (await other_client.delete(f"/api/assets/{source['id']}")).status_code == 404
assert all(path.exists() for path in source_files)
assert (await system.client.delete(f"/api/assets/{source['id']}")).status_code == 204
assert all(not path.exists() for path in source_files)
async with system.app.state.db.session() as session:
assert (await session.get(SharedAsset, shared["id"])).source_asset_id is None
assert (await other_client.get(shared["preview_url"])).content == png_bytes
assert (await other_client.delete(f"/api/shared-assets/{shared['id']}")).status_code == 404
assert all(path.exists() for path in snapshot_files)
response = await system.client.delete(f"/api/shared-assets/{shared['id']}")
assert response.status_code == 204, response.text
assert all(not path.exists() for path in snapshot_files)
async with system.app.state.db.session() as session:
assert await session.get(SharedAsset, shared["id"]) is None
assert await session.get(Asset, snapshot_id) is None
for model in (AssetReference, AssetTag):
assert await session.scalar(select(model).where(model.asset_id == snapshot_id)) is None
assert (await system.client.delete(f"/api/shared-assets/{shared['id']}")).status_code == 404
for client, asset in imports:
assert (await client.get(asset["preview_url"])).content == png_bytes
assert (await client.get(asset["thumbnail_url"])).status_code == 200
assert (await imports[0][0].delete(f"/api/assets/{imports[0][1]['id']}")).status_code == 204
assert all(not path.exists() for path in imported_files[0])
assert all(path.exists() for path in imported_files[1])
assert (await other_client.get(imports[1][1]["preview_url"])).content == png_bytes
async def test_missing_bytes_do_not_prevent_delete_retry(system, png_bytes):
asset = await upload(system, png_bytes)
paths = await files_for(system, asset["id"])
paths[0].unlink()
assert (await system.client.delete(f"/api/assets/{asset['id']}")).status_code == 204
assert all(not path.exists() for path in paths)
async with system.app.state.db.session() as session:
assert await session.get(Asset, asset["id"]) is None
@pytest.mark.parametrize("field", ["storage_key", "thumbnail_key"])
async def test_outside_key_rejects_delete_before_any_owned_bytes_are_removed(
system, png_bytes, tmp_path, field
):
asset = await upload(system, png_bytes)
paths = await files_for(system, asset["id"])
outside = tmp_path / "keep.png"
outside.write_bytes(b"must survive")
async with system.app.state.db.session() as session:
setattr(await session.get(Asset, asset["id"]), field, str(outside))
await session.commit()
response = await system.client.delete(f"/api/assets/{asset['id']}")
assert response.status_code == 409, response.text
assert outside.read_bytes() == b"must survive"
assert all(path.exists() for path in paths)
async def test_key_for_another_asset_cannot_delete_its_files(system, png_bytes):
first, second = await upload(system, png_bytes), await upload(system, png_bytes)
paths = await files_for(system, second["id"])
async with system.app.state.db.session() as session:
(await session.get(Asset, first["id"])).thumbnail_key = (
await session.get(Asset, second["id"])
).thumbnail_key
await session.commit()
assert (await system.client.delete(f"/api/assets/{first['id']}")).status_code == 409
assert all(path.exists() for path in paths)
async def test_symlink_cannot_delete_outside_bytes(system, png_bytes, tmp_path):
asset = await upload(system, png_bytes)
original, thumbnail = await files_for(system, asset["id"])
outside = tmp_path / "keep.png"
outside.write_bytes(b"must survive")
thumbnail.unlink()
try:
thumbnail.symlink_to(outside)
except OSError as exc:
pytest.skip(f"Symlinks unavailable: {exc}")
response = await system.client.delete(f"/api/assets/{asset['id']}")
assert response.status_code == 409, response.text
assert outside.read_bytes() == b"must survive" and original.exists()
@pytest.mark.parametrize("key", ["", "."])
async def test_empty_or_directory_key_cannot_remove_root(system, png_bytes, key):
asset = await upload(system, png_bytes)
paths = await files_for(system, asset["id"])
async with system.app.state.db.session() as session:
(await session.get(Asset, asset["id"])).storage_key = key
await session.commit()
assert (await system.client.delete(f"/api/assets/{asset['id']}")).status_code == 409
assert system.settings.asset_root.is_dir() and all(path.exists() for path in paths)
@pytest.mark.parametrize("protected", ["draft", "producer", "execution"])
async def test_live_references_and_producer_protect_files(system, png_bytes, protected):
asset = await upload(system, png_bytes)
paths = await files_for(system, asset["id"])
job = (
await system.client.post(
"/api/jobs", json={"task_type": "image.generate", "input": {"prompt": "cup"}}
)
).json()["jobs"][0]
async with system.app.state.db.session() as session:
row = await session.get(Asset, asset["id"])
if protected == "draft":
session.add(
AssetReference(
owner_id=row.owner_id, asset_id=row.id, ref_kind="draft", ref_id="draft"
)
)
elif protected == "producer":
row.source_job_id = job["id"]
else:
execution = Execution(
job_id=job["id"],
ordinal=1,
phase_key="execute",
resource_pool="cpu_media",
fence_token="test",
state="running",
)
session.add(execution)
await session.flush()
session.add(
AssetReference(
owner_id=row.owner_id,
asset_id=row.id,
ref_kind="execution",
ref_id=execution.id,
)
)
await session.commit()
assert (await system.client.delete(f"/api/assets/{asset['id']}")).status_code == 409
assert all(path.exists() for path in paths)
@pytest.mark.skipif(os.name != "nt", reason="Native Windows file sharing denial")
@pytest.mark.parametrize("shared", [False, True])
async def test_windows_locked_file_returns_failure_then_retry_cleans_files(
system, png_bytes, shared
):
import ctypes
from ctypes import wintypes
asset = await upload(system, png_bytes)
if shared:
publication = (await system.client.post(f"/api/assets/{asset['id']}/publish")).json()
route = f"/api/shared-assets/{publication['id']}"
async with system.app.state.db.session() as session:
asset_id = (await session.get(SharedAsset, publication["id"])).asset_id
else:
route, asset_id = f"/api/assets/{asset['id']}", asset["id"]
paths = await files_for(system, asset_id)
kernel = ctypes.WinDLL("kernel32", use_last_error=True)
kernel.CreateFileW.argtypes = [
wintypes.LPCWSTR,
wintypes.DWORD,
wintypes.DWORD,
wintypes.LPVOID,
wintypes.DWORD,
wintypes.DWORD,
wintypes.HANDLE,
]
kernel.CreateFileW.restype = wintypes.HANDLE
kernel.CloseHandle.argtypes = [wintypes.HANDLE]
# Lock the thumbnail, so a retry must also tolerate an already removed original.
handle = kernel.CreateFileW(str(paths[1]), 0x80000000, 1, None, 3, 0x80, None)
assert handle != wintypes.HANDLE(-1).value
try:
response = await system.client.delete(route)
assert response.status_code == 503, response.text
assert paths[1].exists()
async with system.app.state.db.session() as session:
assert await session.get(Asset, asset_id) is not None
finally:
kernel.CloseHandle(handle)
assert (await system.client.delete(route)).status_code == 204
assert all(not path.exists() for path in paths)