"""分镜工作台(模块 02)回归用例:锁定本轮 UI/接口整改中发现并修复的缺陷。 覆盖 - PATCH 镜头必须允许显式清空可空字段(seed),否则「填过就改不回去」; - 枚举字段(mode/shot_size/…)与时长必须校验:写脏值过去是 200 静默降级, 现在要 400 并说明可选值; - 镜号唯一冲突必须是 400 业务错误,不能把 SQLAlchemy IntegrityError 抛成 500; - 批量操作 /shots/bulk:复制要插在来源之后并重排镜号,移动支持绝对落点, patch 统一改字段要重算提示词且拒绝镜号,删除后镜号连续; - 轻量列表 /shots/board 必须自带逐镜预检结论,且不带提示词版本等重字段; - /shots/{id} 单镜头详情、/shots/export 三种格式可被导入器再次吃回去。 """ from __future__ import annotations import pytest from tests.conftest import absolute SCRIPT = """# 镜头 1:启航 画面: 星舰舰桥,林澈凝视全息星图 景别: 中景 运镜: 推镜 时长: 2 台词: 我们出发吧 说话人: 林澈 出镜角色: 林澈 场景: 星舰舰桥 # 镜头 2:跃迁 画面: 星舰跃入蓝色虫洞,光带在舷窗外拉长 景别: 大远景 运镜: 拉镜 时长: 3 台词: 前方就是目标 说话人: 林澈 出镜角色: 林澈 # 镜头 3:抵达 画面: 陌生行星的红色荒漠与远处殖民灯光 景别: 全景 运镜: 移镜 时长: 2 出镜角色: 林澈 """ @pytest.fixture def project_with_shots(api, studio): """工作台用例统一从「已导入 3 个镜头」的状态开始。""" pid = studio["project_id"] body = api.post(f"/api/projects/{pid}/import", data={"script_text": SCRIPT, "default_duration": "2"})["result"] assert body["created"] == 3, body return pid def _shots(api, pid): return api.get(f"/api/projects/{pid}/shots")["shots"] def test_patch_allows_explicit_clear_of_nullable_fields(api, project_with_shots): """seed 这类可空字段:清空必须写回 NULL,而不是被静默忽略。""" pid = project_with_shots sid = _shots(api, pid)[0]["id"] assert api.patch(f"/api/projects/{pid}/shots/{sid}", json={"seed": 42})["result"]["seed"] == 42 assert api.patch(f"/api/projects/{pid}/shots/{sid}", json={"seed": None})["result"]["seed"] is None # 未出现在补丁里的字段不受影响(exclude_unset 语义仍然成立) api.patch(f"/api/projects/{pid}/shots/{sid}", json={"title": "改标题"}) assert api.patch(f"/api/projects/{pid}/shots/{sid}", json={"dialogue": "保持"})["result"]["seed"] is None def test_shot_enum_and_duration_are_validated(api, project_with_shots): """脏枚举/非法时长过去会静默写库并降级出片,现在必须挡住。""" pid = project_with_shots sid = _shots(api, pid)[0]["id"] bad = api.call("PATCH", f"/api/projects/{pid}/shots/{sid}", expect=400, json={"mode": "nope"}) assert "mode" in bad["detail"] and "i2v" in bad["detail"] api.call("PATCH", f"/api/projects/{pid}/shots/{sid}", expect=400, json={"duration": 0}) api.call("PATCH", f"/api/projects/{pid}/shots/{sid}", expect=400, json={"shot_size": "huge"}) api.call("POST", f"/api/projects/{pid}/shots", expect=400, json={"title": "非法模式", "description": "一段足够长的画面描述用于通过预检", "mode": "v2v"}) untouched = _shots(api, pid)[0] assert untouched["mode"] == "i2v" and untouched["duration"] > 0 def test_duplicate_shot_code_is_business_error_not_500(api, project_with_shots): """镜号唯一是用户可修复的错误:必须 400 + 可读原因,不能 500。""" pid = project_with_shots shots = _shots(api, pid) api.call("PATCH", f"/api/projects/{pid}/shots/{shots[0]['id']}", expect=400, json={"code": shots[1]["code"]}) api.call("POST", f"/api/projects/{pid}/shots", expect=400, json={"title": "撞号", "code": shots[0]["code"], "description": "另一个镜头的画面描述内容"}) assert _shots(api, pid)[0]["code"] != shots[1]["code"] # 失败不能留下半个写入 def test_bulk_duplicate_inserts_after_source_and_resequences(api, project_with_shots): """复制必须紧跟来源镜头,且镜号连续无断号(工作台最常用的动作)。""" pid = project_with_shots before = _shots(api, pid) source = before[1] res = api.post(f"/api/projects/{pid}/shots/bulk", json={"action": "duplicate", "shot_ids": [source["id"]]})["result"] assert res["count"] == 1 and len(res["created"]) == 1 order = _shots(api, pid) assert [s["order_index"] for s in order] == list(range(1, len(order) + 1)) clone = next(s for s in order if s["id"] in res["created"]) assert clone["order_index"] == source["order_index"] + 1 assert clone["title"].endswith("副本") assert clone["code"] not in {s["code"] for s in before} assert [c["id"] for c in clone["characters"]] == [c["id"] for c in source["characters"]] assert clone["output_url"] == "" and clone["status"] != "approved" # 副本不得继承产物 def test_bulk_move_absolute_and_relative(api, project_with_shots): pid = project_with_shots order = _shots(api, pid) last = order[-1] api.post(f"/api/projects/{pid}/shots/bulk", json={"action": "move", "shot_ids": [last["id"]], "index": 1}) assert _shots(api, pid)[0]["id"] == last["id"] api.post(f"/api/projects/{pid}/shots/bulk", json={"action": "move", "shot_ids": [last["id"]], "delta": 1}) assert _shots(api, pid)[1]["id"] == last["id"] assert [s["order_index"] for s in _shots(api, pid)] == list(range(1, len(order) + 1)) def test_bulk_patch_updates_fields_and_recomposes_prompt(api, project_with_shots): pid = project_with_shots shots = _shots(api, pid) ids = [s["id"] for s in shots] api.post(f"/api/projects/{pid}/shots/bulk", json={"action": "patch", "shot_ids": ids, "fields": {"duration": 2.5, "shot_size": "wide"}}) after = {s["id"]: s for s in _shots(api, pid)} for sid in ids: assert after[sid]["duration"] == 2.5 assert "远景" in after[sid]["prompt"] # 结构性字段变更要重算提示词 assert "时长约 2 秒" in after[sid]["prompt"] api.call("POST", f"/api/projects/{pid}/shots/bulk", expect=400, json={"action": "patch", "shot_ids": ids[:1], "fields": {"shot_size": "nope"}}) api.call("POST", f"/api/projects/{pid}/shots/bulk", expect=400, json={"action": "patch", "shot_ids": ids[:1], "fields": {"code": "9"}}) api.call("POST", f"/api/projects/{pid}/shots/bulk", expect=400, json={"action": "patch", "shot_ids": ids[:1], "fields": {}}) api.call("POST", f"/api/projects/{pid}/shots/bulk", expect=400, json={"action": "patch", "shot_ids": ids[:1], "fields": {"status": "approved"}}) def test_bulk_delete_keeps_order_contiguous(api, project_with_shots): pid = project_with_shots ids = [s["id"] for s in _shots(api, pid)] api.post(f"/api/projects/{pid}/shots/bulk", json={"action": "delete", "shot_ids": ids[:1]}) rest = _shots(api, pid) assert len(rest) == len(ids) - 1 assert [s["order_index"] for s in rest] == list(range(1, len(rest) + 1)) api.call("POST", f"/api/projects/{pid}/shots/bulk", expect=400, json={"action": "delete", "shot_ids": []}) api.call("POST", f"/api/projects/{pid}/shots/bulk", expect=404, json={"action": "delete", "shot_ids": [999999]}) def test_board_endpoint_is_light_and_carries_preflight(api, project_with_shots, make_image_png): """看板视图必须自带预检结论(前端靠它显示阻塞原因),且不回吐重字段。""" pid = project_with_shots shots = _shots(api, pid) board = api.get(f"/api/projects/{pid}/shots/board") assert board["count"] == len(shots) assert board["planned_duration"] > 0 assert board["preflight"]["total"] == len(shots) first = board["shots"][0] assert "prompt" not in first and "prompt_revisions" not in first and "assets" not in first assert first["prompt_length"] > 0 assert isinstance(first["ready"], bool) assert "issues" in first and "keyframe_url" in first # 关键帧上传后看板要立刻反映(i2v 缺关键帧是阻塞项) blocked = next(s for s in board["shots"] if not s["ready"]) assert any(i["severity"] == "error" for i in blocked["issues"]) api.post(f"/api/projects/{pid}/shots/{blocked['id']}/assets", files={"file": ("kf.png", make_image_png(), "image/png")}, data={"kind": "keyframe", "name": "关键帧"}) fixed = next(s for s in api.get(f"/api/projects/{pid}/shots/board")["shots"] if s["id"] == blocked["id"]) assert fixed["keyframe_url"].startswith("/media/") def test_single_shot_detail_and_exports(api, project_with_shots): pid = project_with_shots sid = _shots(api, pid)[0]["id"] shot = api.get(f"/api/projects/{pid}/shots/{sid}")["shot"] assert shot["id"] == sid and shot["prompt"] and "assets" in shot and "prompt_revisions" in shot api.call("GET", f"/api/projects/{pid}/shots/999999", expect=404) md = api.call("GET", f"/api/projects/{pid}/shots/export?fmt=md") assert md.headers["content-type"].startswith("text/plain") body = md.text assert "# 镜头 1" in body and "画面:" in body # 导出结果必须能被导入器再吃回去(脚本 ↔ 分镜双向可逆) reimported = api.post(f"/api/projects/{pid}/import", data={"script_text": body, "dry_run": "true"})["result"] assert reimported["parsed"] == len(_shots(api, pid)) assert [x["dialogue"] for x in reimported["shots"]] == [x["dialogue"] for x in _shots(api, pid)] csv_resp = api.call("GET", f"/api/projects/{pid}/shots/export?fmt=csv") assert "镜号" in csv_resp.text.splitlines()[0] payload = api.get("/api/projects/%s/shots/export?fmt=json" % pid) assert payload["count"] == len(_shots(api, pid)) assert {"code", "description", "characters", "scene"} <= set(payload["shots"][0]) def test_deleting_a_shot_purges_its_assets(api, db, project_with_shots, make_image_png): """删除镜头要连带清理镜头级素材,否则脏资产会跟着被复用的主键「投胎」到新镜头。 实测事故:删掉 3 个镜头后重新下达指令,新镜头拿回了同样的 id, 于是上一轮的关键帧被当成「本镜头已有首帧」,预检通过、调度直接跳过补帧, 最后用旧画面渲染了新台词。 """ from app.models import Asset from app.services import storage as storage_service pid = project_with_shots victim = _shots(api, pid)[-1] # 删最大 id:新建镜头必然复用同一个主键 uploaded = api.post(f"/api/projects/{pid}/shots/{victim['id']}/assets", files={"file": ("kf.png", make_image_png(), "image/png")}, data={"kind": "keyframe", "name": "关键帧"})["result"] keyframe_path = uploaded["asset"]["path"] assert absolute(keyframe_path).exists() api.delete(f"/api/projects/{pid}/shots/{victim['id']}") assert not absolute(keyframe_path).exists(), "镜头删除后关键帧文件要一起清理" assert api.get(f"/api/projects/{pid}/assets", params={"owner_type": "shot", "owner_id": victim["id"]})["count"] == 0 created = api.post(f"/api/projects/{pid}/shots", json={"title": "补拍的镜头", "description": "全新的画面", "mode": "i2v", "shot_size": "medium", "camera_angle": "eye_level", "camera_movement": "push_in", "duration": 2})["result"] assert created["id"] == victim["id"], "SQLite 会复用主键,这正是脏资产的来源" fresh = next(s for s in api.get(f"/api/projects/{pid}/shots/board")["shots"] if s["id"] == created["id"]) assert fresh["keyframe_url"] == "" and fresh["asset_count"] == 0 def test_asset_older_than_its_shot_is_ignored(api, db, project_with_shots, make_image_png): """库里已经存在的历史脏资产(比宿主镜头还老)不能被当成首帧。""" from datetime import timedelta from app.models import Asset, Shot, now_utc from app.services import storage as storage_service pid = project_with_shots target = _shots(api, pid)[0] uploaded = api.post(f"/api/projects/{pid}/shots/{target['id']}/assets", files={"file": ("old.png", make_image_png(), "image/png")}, data={"kind": "keyframe", "name": "上一轮残留的关键帧"})["result"] keyframe_path = uploaded["asset"]["path"] assert absolute(keyframe_path).exists() row = next(s for s in api.get(f"/api/projects/{pid}/shots/board")["shots"] if s["id"] == target["id"]) assert row["keyframe_url"], "正常上传的关键帧应当显示为首帧缩略图" # 模拟「镜头被删掉后主键复用」:文件与资产行都在,但它们属于上一世的镜头 stale = db.get(Asset, uploaded["asset"]["id"]) # 上一世留下的素材,创建和最后一次写入都早于现任宿主; # 只有 created_at 老、updated_at 新的,是刚被重新导入顶上的,属于正常数据。 stale.created_at = stale.updated_at = now_utc() - timedelta(hours=1) db.commit() assert storage_service.as_utc(stale.created_at) < storage_service.as_utc( db.get(Shot, target["id"]).created_at) row = next(s for s in api.get(f"/api/projects/{pid}/shots/board")["shots"] if s["id"] == target["id"]) assert row["keyframe_url"] == "", "比镜头还老的关键帧是脏数据,不能显示成已有首帧" assert any(i["code"] == "missing_keyframe" for i in row["issues"]), "预检必须继续把它当缺帧处理"