Files
aigc-home/calliope-backend/tests/test_storyboard_fixed_document.py
T

258 lines
8.6 KiB
Python

"Storyboard saved values, physical links, unknown identities and fail-closed binding."
import copy
import hashlib
import json
import subprocess
from pathlib import Path
import pytest
from calliope.comfyui.fixed_document import DEFINITIONS, canonical
from calliope.comfyui.library import build_document
from calliope.comfyui.source_reviews import review_for
REPO = Path(__file__).resolve().parents[2]
OUT = REPO / "docs/hel-892/storyboard-document-evidence"
PATH = next(p for p in DEFINITIONS if p.endswith("/手动按分镜视频截取.json"))
SOURCE = json.loads((REPO / PATH).read_bytes())
REVIEW = review_for(PATH, hashlib.sha1((REPO / PATH).read_bytes()).hexdigest())
BLOCK = REVIEW["fixed_version_document"]
def pointer(obj, path):
for part in path.strip("/").split("/"):
obj = obj[int(part)] if isinstance(obj, list) else obj[part]
return obj
def doc(source=None, review=None):
return build_document(
PATH,
SOURCE if source is None else source,
None,
None,
[],
REVIEW if review is None else review,
)
def refuse(s, r):
r["fixed_version_document"]["canonical_sha256"] = hashlib.sha256(canonical(s)).hexdigest()
r["caller_digest"] = hashlib.sha256(canonical(r["fixed_version_document"])).hexdigest()
assert not doc(s, r)["fixed_version"]["matched"]
@pytest.mark.parametrize("f", BLOCK["fields"], ids=lambda f: f["node_id"] + "." + f["field"])
def test_each_saved_value_type_pointer_and_exact_evidence(f):
v = pointer(SOURCE, f["pointer"])
assert canonical(v) == canonical(f["value"]) and type(v).__name__ == f["json_type"]
for k in [
"label",
"type",
"schema_default",
"unit",
"limits",
"effect",
"execution_note",
"role",
]:
assert f[k]
for k in f["evidence"]:
e = BLOCK["sources"][k]
raw = (OUT / e["local_file"]).read_bytes()
assert hashlib.sha256(raw).hexdigest() == e["sha256"]
assert 1 <= e["lines"][0] <= e["lines"][1] <= len(raw.decode().splitlines())
assert len(e["commit"]) == 40 or e["git_commit_binding"] == "unknown"
@pytest.mark.parametrize("f", BLOCK["fields"], ids=lambda f: f["node_id"] + "." + f["field"])
@pytest.mark.parametrize("variant", ["value", "type", "text"])
def test_each_saved_position_refuses_forged_source_or_definition(f, variant):
s, r = copy.deepcopy(SOURCE), copy.deepcopy(REVIEW)
b = r["fixed_version_document"]
bf = next(x for x in b["fields"] if x["pointer"] == f["pointer"])
if variant == "text":
bf["limits"] = "forged"
else:
parent, _, key = f["pointer"].rpartition("/")
target = pointer(s, parent)
target[int(key) if isinstance(target, list) else key] = (
"forged" if variant == "type" else None
)
bf["value"] = pointer(s, f["pointer"])
bf["json_type"] = type(bf["value"]).__name__
refuse(s, r)
@pytest.mark.parametrize("i", range(22))
@pytest.mark.parametrize("variant", ["mode", "identity"])
def test_each_node_mode_and_identity_bound(i, variant):
s, r = copy.deepcopy(SOURCE), copy.deepcopy(REVIEW)
n = s["nodes"][i]
if variant == "mode":
n["mode"] = 0 if n["mode"] == 4 else 4
else:
n["properties"]["ver"] = "forged"
refuse(s, r)
@pytest.mark.parametrize("i", range(24))
def test_each_physical_endpoint_bound_both_directions(i):
s, r = copy.deepcopy(SOURCE), copy.deepcopy(REVIEW)
s["links"][i][3] = 99999
refuse(s, r)
@pytest.mark.parametrize(
"variant",
[
"empty_info",
"empty_loop",
"missing_bypasser",
"missing_audio_value",
"history",
"comment",
"summary",
"citation",
"source_sha",
"path",
"layout",
"ue",
"frontend",
],
)
def test_special_shapes_history_comments_and_restoration_bound(variant):
s, r = copy.deepcopy(SOURCE), copy.deepcopy(REVIEW)
ns = {n["id"]: n for n in s["nodes"]}
b = r["fixed_version_document"]
if variant == "empty_info":
ns[27]["widgets_values"] = []
elif variant == "empty_loop":
ns[20]["widgets_values"] = {}
elif variant == "missing_bypasser":
ns[15]["widgets_values"] = []
elif variant == "missing_audio_value":
ns[36]["widgets_values"].append("")
elif variant == "history":
ns[10]["widgets_values"]["videopreview"]["params"]["frame_rate"] = 30
elif variant == "comment":
ns[35]["widgets_values"][0] = "forged"
elif variant == "summary":
b["user_overview"] = "already executed"
elif variant == "citation":
b["sources"][0]["sha256"] = "0" * 64
elif variant == "source_sha":
b["source_sha1"] = "0" * 40
elif variant == "path":
b["source_path"] = "forged"
elif variant == "layout":
ns[8]["pos"][0] += 1
elif variant == "ue":
ns[8]["properties"]["ue_properties"]["version"] = "forged"
else:
s["extra"]["frontendVersion"] = "forged"
refuse(s, r)
def test_precise_inventory_connections_and_limits():
ns = {n["id"]: n for n in SOURCE["nodes"]}
b = BLOCK
assert len(ns) == 22 and len(SOURCE["links"]) == 24
assert {i for i, n in ns.items() if n["mode"] == 0} == {8, 18, 21, 29, 10, 15, 5, 35, 13, 6}
assert {i for i, n in ns.items() if n["mode"] == 4} == {
28,
27,
30,
25,
20,
19,
22,
31,
24,
26,
1,
36,
}
assert (
ns[27]["widgets_values"] == {}
and ns[20]["widgets_values"] == []
and "widgets_values" not in ns[15]
)
assert ns[36]["widgets_values"] == ["tmp/audio"]
assert ns[18]["widgets_values"] == [16] and type(ns[18]["widgets_values"][0]) is int
assert ns[29]["widgets_values"] == ns[30]["widgets_values"] == ["每批截取帧数"]
assert not any(
k in ns[29]["properties"] or k in ns[30]["properties"] for k in ["cnr_id", "ver"]
)
assert len(b["fields"]) == len({f["pointer"] for f in b["fields"]}) == 50
assert sum(isinstance(f["value"], dict) for f in b["fields"]) == 4
assert sum(not isinstance(f["value"], dict) for f in b["fields"]) == 46
assert len(b["comments"]) == 2
for e, src, slot, dst, inp, _ in SOURCE["links"]:
assert e in ns[src]["outputs"][slot]["links"] and ns[dst]["inputs"][inp]["link"] == e
for nid, name, e in [
(8, "skip_first_images", 19),
(8, "image_load_cap", 20),
(10, "filename_prefix", 21),
(10, "frame_rate", 23),
(1, "force_rate", 26),
(25, "force_rate", 45),
(25, "skip_first_frames", 38),
(25, "frame_load_cap", 50),
(19, "total", 29),
]:
assert next(x for x in ns[nid]["inputs"] if x["name"] == name)["link"] == e
assert all(
x["link"] is None for x in ns[10]["inputs"] if x["name"] in ["audio", "vae", "meta_batch"]
)
assert ns[1]["outputs"][0]["links"] in ([], None)
assert next(x for x in ns[26]["inputs"] if x["name"] == "caption")["link"] is None
d = doc()
assert d["fixed_version"]["matched"]
assert d["dependencies"]["check_state"] == "unchecked" and d["status"] == dict(
imported=True, doc_done=False, exec_verified=False
)
for c in b["comments"]:
assert pointer(SOURCE, c["pointer"]) == [c["text"]]
assert next(n for n in d["source_notes"] if str(n["node_id"]) == c["node_id"])[
"content"
] == [c["text"]]
assert not b["counts"]["final_prompt_constructed"]
for word in [
"原前端",
"purge_cache",
"caption",
"audioUI",
"每批截取帧数",
"不模拟",
"历史",
"30",
"16",
"1|2",
]:
assert word in " ".join(b["flow"])
def test_old_review_objects_and_27_documents_unchanged():
resource = "calliope-backend/src/calliope/comfyui/source_reviews.json"
old = json.loads(subprocess.check_output(["git", "show", "2a82f1f:" + resource], cwd=REPO))
now = json.loads((REPO / resource).read_bytes())
now[PATH].pop("fixed_version_document")
assert now == old and len(DEFINITIONS) == 28
blocks = [r["fixed_version_document"] for r in old.values() if "fixed_version_document" in r]
assert (
len(blocks) == 27
and sum(len(b["fields"]) for b in blocks) == 838
and sum(
len(
build_document(p, json.loads((REPO / p).read_bytes()), None, None, [], r)[
"source_notes"
]
)
for p, r in old.items()
if "fixed_version_document" in r
)
== 19
)
assert review_for(PATH, "0" * 40) is None