"""素材版本管理用例:删除某个版本 / 将某个版本设为当前版本。 覆盖平台母版(`PlatformMedia`)与项目资产(`Asset`)两侧——它们共用 `app.services.versions`,所以两条链路的语义必须一致: - 「设为当前版本」不只是改 `current_version` 这个数字,父行的 `path/checksum/size_bytes/width/height` 必须一起换,否则引入项目、 生成参考图仍然取到旧文件; - 「删除版本」删的是历史,不能误删当前版本仍在用的物理文件; 删的正好是当前版本时要自动回落,只剩一个版本时要拒绝而不是删空。 """ from __future__ import annotations import pytest from sqlalchemy import text from app.db import SessionLocal from app.models import Asset, EventLog, GenerationRecord, PlatformMedia from app.services import ffmpeg as ff, storage from tests.conftest import _make_image_png needs_probe = pytest.mark.skipif(not ff.available(), reason="需要 ffmpeg/ffprobe 才能校验版本级宽高") # ------------------------------------------------------------------ 小工具 def _rows(sql: str, **params) -> list: """独立短会话读库:避免和 TestClient 的事务共享快照,看到旧数据。""" with SessionLocal() as session: try: return [tuple(row) for row in session.execute(text(sql), params)] finally: session.rollback() def _scalar(sql: str, **params): rows = _rows(sql, **params) return rows[0][0] if rows else None def _exists(path: str) -> bool: return storage.to_absolute(path).exists() def _upload_platform(api, owner_id, *, name="定妆图", width=180, height=180, color="0x224466", kind="portrait"): return api.post( f"/api/platform/characters/{owner_id}/media", files={"file": (f"{name}.png", _make_image_png(width, height, color), "image/png")}, data={"kind": kind, "name": name}, )["result"] def _character(api, name="郭靖"): return api.post("/api/platform/characters", json={"name": name, "role": "主角"})["result"] def _upload_project(api, studio, *, name="定妆图", width=200, height=260, color="0x113355"): pid, cid = studio["project_id"], studio["character_id"] return api.post(f"/api/projects/{pid}/characters/{cid}/assets", files={"file": (f"{name}.png", _make_image_png(width, height, color), "image/png")}, data={"kind": "portrait", "name": name})["result"] def _media_events(action: str) -> list[EventLog]: with SessionLocal() as session: return session.query(EventLog).filter(EventLog.action == action).order_by(EventLog.id).all() # ------------------------------------------------------------------ 1. 序列化契约 @needs_probe def test_media_dict_exposes_version_metadata(api): """版本列表要能支撑 UI:每版的地址/宽高/文件是否在/是否当前 + 顶层 scope。""" human = _character(api) media = _upload_platform(api, human["id"], width=160, height=160, color="0x224466") media = _upload_platform(api, human["id"], width=240, height=320, color="0x993355") assert media["scope"] == "platform" assert media["version"] == 2 assert [v["version_no"] for v in media["versions"]] == [2, 1] current = [v for v in media["versions"] if v["current"]] assert len(current) == 1 and current[0]["version_no"] == 2 for version in media["versions"]: assert version["url"].startswith("/media/") assert version["exists"] is True assert version["width"] and version["height"] assert version["size_bytes"] > 0 assert version["created_at"] # ------------------------------------------------------------------ 2. 设为当前版本 def test_set_current_switches_file_pointer_and_metadata(api): human = _character(api) first = _upload_platform(api, human["id"], width=160, height=160, color="0x224466") second = _upload_platform(api, human["id"], width=240, height=320, color="0x993355") media_id = second["id"] v1 = next(v for v in second["versions"] if v["version_no"] == 1) assert second["path"] == next(v for v in second["versions"] if v["version_no"] == 2)["path"] result = api.post(f"/api/platform/media/{media_id}/versions/1/current", json={"actor": "tester"})["result"] assert result["scope"] == "platform" and result["changed"] is True assert result["previous_version"] == 2 and result["current_version"] == 1 assert result["path"] == v1["path"] and result["url"] == v1["url"] refreshed = api.get(f"/api/platform/media?owner_type=human&owner_id={human['id']}") row = next(item for item in refreshed["items"] if item["id"] == media_id) assert row["version"] == 1 assert row["path"] == v1["path"], "父行文件指针必须跟着切,否则下游仍取到 v2" assert row["checksum"] == v1["checksum"] assert (row["width"], row["height"]) == (v1["width"], v1["height"]) assert _scalar("SELECT path FROM platform_media WHERE id = :mid", mid=media_id) == v1["path"] logged = _media_events("platform.media.version.current") assert len(logged) == 1 and logged[0].actor == "tester" assert logged[0].data_json["previous_version"] == 2 def test_set_current_is_idempotent_and_does_not_log_again(api): human = _character(api) _upload_platform(api, human["id"]) media = _upload_platform(api, human["id"], width=260, height=200, color="0x228855") api.post(f"/api/platform/media/{media['id']}/versions/2/current", json={})["result"] before = len(_media_events("platform.media.version.current")) again = api.post(f"/api/platform/media/{media['id']}/versions/2/current", json={})["result"] assert again["changed"] is False and again["current_version"] == 2 assert len(_media_events("platform.media.version.current")) == before, "重复设为当前不该刷事件" def test_set_current_rejects_unknown_or_missing_version(api): human = _character(api) _upload_platform(api, human["id"]) media = _upload_platform(api, human["id"], width=200, height=200, color="0x551133") missing = api.post(f"/api/platform/media/{media['id']}/versions/9/current", json={}, expect=404) assert "可用版本" in missing["detail"] and "v1" in missing["detail"] # 物理文件被外部清理掉:切过去会立刻白图,必须提前拒绝而不是留下坏当前版本 target = next(v for v in media["versions"] if v["version_no"] == 1) assert storage.delete_media_file(target["path"]) is True broken = api.post(f"/api/platform/media/{media['id']}/versions/1/current", json={}, expect=400) assert "文件已丢失" in broken["detail"] assert api.get(f"/api/platform/media?owner_id={human['id']}")["items"][0]["version"] == 2 unknown_media = api.post("/api/platform/media/999999/versions/1/current", json={}, expect=404) assert "不存在" in unknown_media["detail"] @needs_probe def test_set_current_drives_downstream_reference(api, studio): """下游只看 `path`:切当前版本后,引入项目复制走的必须是新版文件。""" human = _character(api, name="阿拉蕾") _upload_platform(api, human["id"], width=144, height=144, color="0x224466") media = _upload_platform(api, human["id"], width=288, height=288, color="0xcc6622") api.post(f"/api/platform/media/{media['id']}/versions/2/current", json={}) api.post("/api/platform/import", json={"project_id": studio["project_id"], "asset_type": "human", "asset_id": human["id"]}) pid = studio["project_id"] copies = _rows("SELECT a.path, a.width, a.height FROM assets a WHERE a.project_id = :pid " "AND a.kind = 'portrait'", pid=pid) new_copy = [row for row in copies if "platform" in row[0]] assert new_copy, "引入项目时应复制平台定妆图" assert max(int(row[1] or 0) for row in new_copy) == 288, "引入的应是当前版本 v2" # 回落到 v1 后再引入同一个角色:拿到的必须是旧版尺寸 api.post(f"/api/platform/media/{media['id']}/versions/1/current", json={}) api.post("/api/platform/import", json={"project_id": pid, "asset_type": "human", "asset_id": human["id"]}) copies = _rows("SELECT a.path, a.width FROM assets a WHERE a.project_id = :pid AND a.kind = 'portrait'", pid=pid) assert min(int(row[1] or 0) for row in copies if "platform" in row[0]) == 144 # ------------------------------------------------------------------ 3. 删除版本 def test_delete_non_current_version_removes_row_and_file(api): human = _character(api) _upload_platform(api, human["id"], width=160, height=160, color="0x224466") second = _upload_platform(api, human["id"], width=240, height=240, color="0x993355") media = _upload_platform(api, human["id"], width=320, height=200, color="0x1188aa") v1 = next(v for v in media["versions"] if v["version_no"] == 1) result = api.delete(f"/api/platform/media/{media['id']}/versions/1")["result"] assert result["deleted_version"] == 1 and result["was_current"] is False assert result["versions"] == [2, 3] and result["version_count"] == 2 assert result["file_removed"] is True and result["file_kept_reason"] == "" assert result["current_version"] == 3, "删非当前版本不能动当前版本" assert _exists(v1["path"]) is False, "被删版本的物理文件应一起清掉" assert _scalar("SELECT COUNT(*) FROM platform_media_versions WHERE media_id = :mid AND version_no = 1", mid=media["id"]) == 0 assert _media_events("platform.media.version.deleted")[0].data_json["was_current"] is False # 列表接口同步收敛 row = api.get(f"/api/platform/media?owner_id={human['id']}")["items"][0] assert [v["version_no"] for v in row["versions"]] == [3, 2] def test_delete_current_version_falls_back_to_latest_remaining(api): human = _character(api) _upload_platform(api, human["id"], width=160, height=160, color="0x224466") _upload_platform(api, human["id"], width=240, height=240, color="0x993355") media = _upload_platform(api, human["id"], width=320, height=320, color="0x1188aa") v3 = next(v for v in media["versions"] if v["version_no"] == 3) v2 = next(v for v in media["versions"] if v["version_no"] == 2) result = api.delete(f"/api/platform/media/{media['id']}/versions/3")["result"] assert result["was_current"] is True and result["fallback_version"] == 2 assert result["current_version"] == 2 and result["file_removed"] is True assert result["path"] == v2["path"] and _exists(v3["path"]) is False row = api.get(f"/api/platform/media?owner_id={human['id']}")["items"][0] assert row["version"] == 2 and row["path"] == v2["path"] assert (row["width"], row["height"]) == (v2["width"], v2["height"]) assert next(v for v in row["versions"] if v["version_no"] == 2)["current"] is True def test_delete_last_version_is_rejected(api): human = _character(api) media = _upload_platform(api, human["id"]) detail = api.delete(f"/api/platform/media/{media['id']}/versions/1", expect=400)["detail"] assert "只剩" in detail and "直接删除该素材" in detail assert _exists(media["path"]) is True, "拒绝删除时不能顺手删文件" assert api.get(f"/api/platform/media?owner_id={human['id']}")["items"][0]["version"] == 1 def test_delete_version_with_missing_file_is_allowed(api): """文件已被外部清理的坏版本必须能删:预览器只有这条路能清掉「文件缺失」条目, 而「设为当前版本」恰恰会因为文件丢失拒绝它。""" human = _character(api) _upload_platform(api, human["id"], width=180, height=180, color="0x224466") media = _upload_platform(api, human["id"], width=260, height=260, color="0x1188aa") broken = next(v for v in media["versions"] if v["version_no"] == 1) assert storage.delete_media_file(broken["path"]) is True assert api.post(f"/api/platform/media/{media['id']}/versions/1/current", json={}, expect=400)["detail"].count("文件已丢失") == 1 result = api.delete(f"/api/platform/media/{media['id']}/versions/1")["result"] assert result["versions"] == [2] and result["current_version"] == 2 assert result["was_current"] is False and result["file_removed"] is False assert result["file_kept_reason"] == "" row = api.get(f"/api/platform/media?owner_id={human['id']}")["items"][0] assert row["version"] == 2 and [v["version_no"] for v in row["versions"]] == [2] assert next(v for v in row["versions"] if v["version_no"] == 2)["exists"] is True def test_delete_keeps_file_still_referenced_by_another_record(api): """同一文件被多条记录共用时,删一行只能删记录,不能删磁盘。""" human = _character(api) _upload_platform(api, human["id"], width=200, height=200, color="0x224466") media = _upload_platform(api, human["id"], width=210, height=210, color="0x662299") shared = next(v for v in media["versions"] if v["version_no"] == 1)["path"] with SessionLocal() as session: session.execute(text("INSERT INTO platform_media_versions " "(media_id, version_no, path, checksum, source, note, size_bytes, created_at) " "VALUES (:mid, 9, :path, '', 'upload', '共用同一文件', 10, '2026-01-01 00:00:00')"), {"mid": media["id"], "path": shared}) session.commit() # 让当前版本也指向这个共享路径:父行 + v1 + 别的素材都可能依赖它 api.post(f"/api/platform/media/{media['id']}/versions/1/current", json={}) result = api.delete(f"/api/platform/media/{media['id']}/versions/9")["result"] assert result["file_removed"] is False and "仍被" in result["file_kept_reason"] assert "平台素材版本" in result["file_kept_reason"] and "平台素材" in result["file_kept_reason"] assert _exists(shared) is True, "父行还指着这个文件,删了就整张图没了" assert result["current_version"] == 1 and [v["version_no"] for v in result["media"]["versions"]] == [2, 1] def test_delete_keeps_file_referenced_by_generation_record(api): human = _character(api) media = _upload_platform(api, human["id"], width=200, height=200, color="0x224466") _upload_platform(api, human["id"], width=220, height=220, color="0x662288") target = next(v for v in media["versions"] if v["version_no"] == 1) with SessionLocal() as session: session.add(GenerationRecord(project_id=1, kind="generate_shot", prompt="p", asset_paths=[target["path"]])) session.commit() result = api.delete(f"/api/platform/media/{media['id']}/versions/1")["result"] assert result["file_removed"] is False and "生成记录" in result["file_kept_reason"] assert _exists(target["path"]) is True def test_delete_media_itself_still_cleans_everything(api): """整条素材删除(老接口)不能被新逻辑影响。""" human = _character(api) _upload_platform(api, human["id"]) media = _upload_platform(api, human["id"], width=210, height=210, color="0x337788") paths = [v["path"] for v in media["versions"]] body = api.delete(f"/api/platform/media/{media['id']}") assert body["ok"] is True and body["files_removed"] == 2 assert all(not _exists(path) for path in paths) assert _scalar("SELECT COUNT(*) FROM platform_media_versions WHERE media_id = :mid", mid=media["id"]) == 0 # ------------------------------------------------------------------ 4. 项目资产同一套语义 def test_project_asset_set_current_and_delete(api, studio): _upload_project(api, studio, width=200, height=260, color="0x113355") asset = _upload_project(api, studio, width=300, height=180, color="0x773311") assert asset["scope"] == "project" and asset["version"] == 2 v1 = next(v for v in asset["versions"] if v["version_no"] == 1) result = api.post(f"/api/assets/{asset['id']}/versions/1/current", json={"actor": "tester"})["result"] assert result["scope"] == "project" and result["current_version"] == 1 assert result["path"] == v1["path"] stored = api.get(f"/api/projects/{studio['project_id']}/assets")["assets"] row = next(item for item in stored if item["id"] == asset["id"]) assert row["version"] == 1 and row["path"] == v1["path"] and row["scope"] == "project" logged = _media_events("asset.version.current") assert len(logged) == 1 and logged[0].project_id == studio["project_id"] assert logged[0].entity_type == "asset" and logged[0].entity_id == asset["id"] deleted = api.delete(f"/api/assets/{asset['id']}/versions/1")["result"] assert deleted["was_current"] is True and deleted["fallback_version"] == 2 assert deleted["current_version"] == 2 and deleted["file_removed"] is True assert _exists(v1["path"]) is False v2 = next(v for v in deleted["media"]["versions"] if v["version_no"] == 2) with SessionLocal() as session: row = session.get(Asset, asset["id"]) assert row.current_version == 2 and row.path == v2["path"] assert (row.width, row.height) == (v2["width"], v2["height"]) assert _media_events("asset.version.deleted")[0].project_id == studio["project_id"] def test_project_asset_rejects_unknown_version(api, studio): asset = _upload_project(api, studio) assert api.post(f"/api/assets/{asset['id']}/versions/7/current", json={}, expect=404)["detail"] assert "可用版本" in api.post(f"/api/assets/{asset['id']}/versions/7/current", json={}, expect=404)["detail"] assert "只剩" in api.delete(f"/api/assets/{asset['id']}/versions/1", expect=400)["detail"] assert api.delete("/api/assets/987654/versions/1", expect=404)["detail"].endswith("不存在") def test_project_asset_delete_reduces_history(api, studio): _upload_project(api, studio, width=200, height=200, color="0x112233") _upload_project(api, studio, width=210, height=210, color="0x445566") asset = _upload_project(api, studio, width=220, height=220, color="0x778899") old = next(v for v in asset["versions"] if v["version_no"] == 1) result = api.delete(f"/api/assets/{asset['id']}/versions/1")["result"] assert result["versions"] == [2, 3] and _exists(old["path"]) is False row = api.get(f"/api/projects/{studio['project_id']}/assets")["assets"] assert [v["version_no"] for v in next(i for i in row if i["id"] == asset["id"])["versions"]] == [3, 2] # 删掉的版本号可以重新「设为当前」吗?不行:记录已不存在 assert "可用版本" in api.post(f"/api/assets/{asset['id']}/versions/1/current", json={}, expect=404)["detail"] # ------------------------------------------------------------------ 5. 兼容与迁移 @needs_probe def test_legacy_version_rows_without_metadata_can_still_be_promoted(api): """历史版本行没有宽高列(新加的列是 NULL):设为当前时现测,而不是留下脏尺寸。""" human = _character(api) _upload_platform(api, human["id"], width=160, height=160, color="0x224466") media = _upload_platform(api, human["id"], width=240, height=240, color="0x993355") v1 = next(v for v in media["versions"] if v["version_no"] == 1) with SessionLocal() as session: session.execute(text("UPDATE platform_media_versions SET width = NULL, height = NULL, " "duration_ms = NULL, mime = NULL WHERE media_id = :mid AND version_no = 1"), {"mid": media["id"]}) session.commit() result = api.post(f"/api/platform/media/{media['id']}/versions/1/current", json={})["result"] assert result["current_version"] == 1 with SessionLocal() as session: row = session.get(PlatformMedia, media["id"]) assert row.path == v1["path"] assert row.width and row.height, "缺元数据时要现测补齐" def test_version_rows_are_unique_after_delete_then_upload(api): """删版本后版本号不回收:新上传仍要接在最大值后面,别撞唯一约束。""" human = _character(api) _upload_platform(api, human["id"]) media = _upload_platform(api, human["id"], width=200, height=200, color="0x993355") api.delete(f"/api/platform/media/{media['id']}/versions/1") again = _upload_platform(api, human["id"], width=210, height=210, color="0x1177aa") assert again["version"] == 3 assert [row[0] for row in _rows( "SELECT version_no FROM platform_media_versions WHERE media_id = :mid ORDER BY version_no", mid=media["id"])] == [2, 3] with SessionLocal() as session: rows = session.get(PlatformMedia, media["id"]).versions assert len({r.version_no for r in rows}) == len(rows) # ------------------------------------------------------ 声线:参考音频跟随当前版本 # PlatformVoice.provider_voice_id / VoiceAsset.provider_voice_id 存的是「具体某一版的文件」 # (IndexTTS2 直接拿它当克隆参考音频),不是「当前版本」这个概念。 # 换当前版本时如果只改素材父行,页面上写着 v3、配音出来还是 v1 的音色。 def test_platform_voice_reference_follows_current_version(api, db): from app.models import PlatformVoice from tests.test_delivery import _make_wav voice = api.post("/api/platform/voices", json={"name": "郭靖 · 声线"})["result"] media = api.post( f"/api/platform/voice/{voice['id']}/media", files={"file": ("ref.wav", _make_wav(0.4), "audio/wav")}, data={"kind": "reference", "name": "参考音色"}, )["result"] second = api.post( f"/api/platform/voice/{voice['id']}/media", files={"file": ("ref.wav", _make_wav(0.9), "audio/wav")}, data={"kind": "reference", "name": "参考音色"}, )["result"] assert second["id"] == media["id"] and second["version"] == 2 v1_path, v2_path = media["path"], second["path"] row = db.get(PlatformVoice, voice["id"]) row.provider_voice_id = v2_path # 绑定在「当时的当前版本」v2 上 db.commit() result = api.post(f"/api/platform/media/{media['id']}/versions/1/current", json={"actor": "test"})["result"] assert result["voice_references_updated"] == [f"平台声线 #{voice['id']}"] db.expire_all() assert db.get(PlatformVoice, voice["id"]).provider_voice_id == v1_path, "参考音频没跟到 v1" # 删掉正被声线引用的当前版本:先解绑再判引用,文件才不会被自己挡住 # TestClient.delete() 不支持 json 参数,删除要带 actor 就得走 request response = api.client.request("DELETE", f"/api/platform/media/{media['id']}/versions/1", json={"actor": "test"}) assert response.status_code == 200, response.text[:400] deleted = response.json()["result"] assert deleted["fallback_version"] == 2 and deleted["file_removed"] is True assert deleted["voice_references_updated"] == [f"平台声线 #{voice['id']}"] db.expire_all() assert db.get(PlatformVoice, voice["id"]).provider_voice_id == v2_path assert _exists(v1_path) is False and _exists(v2_path) is True events = [event for event in _media_events("platform.media.version.deleted") if event.entity_id == media["id"]] assert "参考音频跟随" in events[-1].message def test_project_voice_reference_follows_current_version(api, studio, db): from app.models import VoiceAsset from tests.test_delivery import _make_wav pid, vid = studio["project_id"], studio["voice_id"] media = api.post( f"/api/projects/{pid}/voices/{vid}/assets", files={"file": ("ref.wav", _make_wav(0.4), "audio/wav")}, data={"kind": "reference", "name": "参考音色"}, )["result"] second = api.post( f"/api/projects/{pid}/voices/{vid}/assets", files={"file": ("ref.wav", _make_wav(0.9), "audio/wav")}, data={"kind": "reference", "name": "参考音色"}, )["result"] assert second["id"] == media["id"] and second["version"] == 2 row = db.get(VoiceAsset, vid) row.provider_voice_id = second["path"] db.commit() result = api.post(f"/api/assets/{media['id']}/versions/1/current", json={"actor": "test"})["result"] assert result["voice_references_updated"] == [f"项目声线 #{vid}"] db.expire_all() assert db.get(VoiceAsset, vid).provider_voice_id == media["path"] assert _scalar("select path from assets where id = :i", i=media["id"]) == media["path"] def test_voice_binding_untouched_when_switching_back_to_same_version(api, db): """重复点「设为当前」不该把声线绑定写一遍,也不该留下事件。""" from app.models import PlatformVoice from tests.test_delivery import _make_wav voice = api.post("/api/platform/voices", json={"name": "阿拉蕾 · 声线"})["result"] media = api.post( f"/api/platform/voice/{voice['id']}/media", files={"file": ("ref.wav", _make_wav(0.4), "audio/wav")}, data={"kind": "reference", "name": "参考音色"}, )["result"] api.post(f"/api/platform/voice/{voice['id']}/media", files={"file": ("ref.wav", _make_wav(0.9), "audio/wav")}, data={"kind": "reference", "name": "参考音色"}) row = db.get(PlatformVoice, voice["id"]) row.provider_voice_id = media["path"] # 指向 v1,而当前是 v2 db.commit() # 当前本来就是 v2:重复设为当前 → 不写库、不动绑定 result = api.post(f"/api/platform/media/{media['id']}/versions/2/current", json={"actor": "test"})["result"] assert result["changed"] is False and result["voice_references_updated"] == [] db.expire_all() assert db.get(PlatformVoice, voice["id"]).provider_voice_id == media["path"], "不该动显式绑定到旧版的声线"