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

212 lines
8.5 KiB
Python

"""One editorial addition: identity refusal, exact positions and media conditions."""
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/concat-document-evidence"
PATHS = [next(p for p in DEFINITIONS if p.endswith(n + ".json")) for n in ["双图像或视频合并显示"]]
SOURCES = [json.loads((REPO / p).read_bytes()) for p in PATHS]
REVIEWS = [review_for(p, hashlib.sha1((REPO / p).read_bytes()).hexdigest()) for p in PATHS]
FIELDS = [(i, f) for i, r in enumerate(REVIEWS) for f in r["fixed_version_document"]["fields"]]
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(i, source=None, review=None):
return build_document(
PATHS[i],
SOURCES[i] if source is None else source,
None,
None,
[],
REVIEWS[i] if review is None else review,
)
@pytest.mark.parametrize("i,field", FIELDS)
def test_exact_positions_and_fixed_text_citations(i, field):
value = pointer(SOURCES[i], field["pointer"])
assert (
canonical(value) == canonical(field["value"]) and type(value).__name__ == field["json_type"]
)
for k in [
"label",
"type",
"schema_default",
"unit",
"limits",
"effect",
"execution_note",
"role",
]:
assert field[k]
for k in field["evidence"]:
e = REVIEWS[i]["fixed_version_document"]["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 and e["commit"] in e["url"]) or e.get(
"git_commit_binding"
) == "unknown"
@pytest.mark.parametrize("i,field", FIELDS)
@pytest.mark.parametrize("variant", ["saved", "type", "text"])
def test_every_position_refuses_even_recomputed_caller_digest(i, field, variant):
s, r = copy.deepcopy(SOURCES[i]), copy.deepcopy(REVIEWS[i])
b = r["fixed_version_document"]
f = next(f for f in b["fields"] if f["pointer"] == field["pointer"])
if variant == "text":
f["schema_default"] = "forged"
else:
parent, _, key = field["pointer"].rpartition("/")
target = pointer(s, parent)
target[int(key) if isinstance(target, list) else key] = (
"forged" if variant == "type" else ("changed-null" if field["value"] is None else None)
)
f["value"] = pointer(s, field["pointer"])
f["json_type"] = type(f["value"]).__name__
b["canonical_sha256"] = hashlib.sha256(canonical(s)).hexdigest()
r["caller_digest"] = hashlib.sha256(canonical(b)).hexdigest()
assert not doc(i, s, r)["fixed_version"]["matched"]
@pytest.mark.parametrize("i", [0])
@pytest.mark.parametrize(
"kind",
[
"edge",
"mode",
"version",
"history",
"missing",
"null",
"list",
"object",
"swap",
"source_sha",
"citation",
"ue",
"empty_node",
"reference",
"preview_missing",
"preview_null",
"preview_object",
],
)
def test_graph_history_shape_and_binding_refuse(i, kind):
s, r = copy.deepcopy(SOURCES[i]), copy.deepcopy(REVIEWS[i])
b = r["fixed_version_document"]
if kind == "edge":
s["links"][0][1] = 999
elif kind == "mode":
s["nodes"][0]["mode"] = 2
elif kind == "version":
s["nodes"][0]["properties"]["ver"] = "forged"
elif kind == "history":
next(n for n in s["nodes"] if n["id"] == 10)["widgets_values"]["videopreview"]["params"][
"filename"
] = "forged"
elif kind in ["missing", "null", "list", "object"]:
values = next(n for n in s["nodes"] if n["id"] == 10)["widgets_values"]
if kind == "missing":
del values["videopreview"]
else:
values["videopreview"] = {"null": None, "list": [], "object": {}}[kind]
elif kind == "swap":
r = copy.deepcopy(
review_for(
next(p for p in DEFINITIONS if p.endswith("视频倒放.json")),
hashlib.sha1(
(
REPO / next(p for p in DEFINITIONS if p.endswith("视频倒放.json"))
).read_bytes()
).hexdigest(),
)
)
elif kind == "source_sha":
r["source_sha"] = "0" * 40
elif kind == "ue":
s["extra"]["ue_links"] = [1]
elif kind == "empty_node":
next(n for n in s["nodes"] if n["id"] == 11)["widgets_values"] = []
elif kind.startswith("preview_"):
n = next(n for n in s["nodes"] if n["id"] == 5)
if kind == "preview_missing":
del n["widgets_values"]
else:
n["widgets_values"] = None if kind == "preview_null" else {}
elif kind == "reference":
s["nodes"][0]["widgets_values"][0] = "forged.png"
else:
b["sources"][0]["sha256"] = "0" * 64
b["canonical_sha256"] = hashlib.sha256(canonical(s)).hexdigest()
r["caller_digest"] = hashlib.sha256(canonical(b)).hexdigest()
assert not doc(i, s, r)["fixed_version"]["matched"]
def test_actual_paths_counts_old_objects_and_media_conditions():
resource = "calliope-backend/src/calliope/comfyui/source_reviews.json"
old = json.loads(subprocess.check_output(["git", "show", "d1ba226:" + resource], cwd=REPO))
now = json.loads((REPO / resource).read_bytes())
multivideo = next(p for p in now if p.endswith("/多视频合成分屏展示.json"))
now[multivideo].pop("fixed_version_document")
watermark = next(p for p in now if p.endswith("/图像4种添加水印节点.json"))
now[watermark].pop("fixed_version_document")
birefnet = next(p for p in now if p.endswith("/birefnet_图像移除背景.json"))
now[birefnet].pop("fixed_version_document")
latent = next(p for p in now if p.endswith("/加载本地latent解码.json"))
now[latent].pop("fixed_version_document")
later = next(p for p in now if p.endswith("/截取视频每一帧.json"))
now[later].pop("fixed_version_document")
b = now[PATHS[0]].pop("fixed_version_document")
d = doc(0)
assert now == old and len(DEFINITIONS) == 26
assert d["fixed_version"]["matched"] and len(b["fields"]) == 42
assert b["comments"] == [] and b["counts"]["history_objects"] == 3
assert b["counts"]["scalar_saved_positions"] == 39
assert b["counts"]["linked_saved_fields"] == 1
assert d["status"] == dict(imported=True, doc_done=False, exec_verified=False)
assert d["dependencies"]["check_state"] == "unchecked"
assert review_for(PATHS[0], "0" * 40) is None
blocks = [r["fixed_version_document"] for r in old.values() if "fixed_version_document" in r]
assert len(blocks) == 20 and sum(len(b["fields"]) for b in blocks) == 576
# One ASR note is kept in flow rather than comments; actual source_notes are checked in GET.
assert sum(len(b.get("comments", [])) for b in blocks) == 14
for step in b["steps"]:
assert step in d["steps"]
g = SOURCES[0]
nodes = {n["id"]: n for n in g["nodes"]}
assert len(nodes) == 9 and len(g["links"]) == 9
for e in g["links"]:
assert e[0] in nodes[e[1]]["outputs"][e[2]]["links"]
assert nodes[e[1]]["outputs"][e[2]]["type"] == e[5]
assert nodes[e[3]]["inputs"][e[4]]["link"] == e[0]
assert nodes[e[3]]["inputs"][e[4]]["type"] == e[5]
assert nodes[5]["widgets_values"] == [] and nodes[11]["widgets_values"] == {}
assert set(n["id"] for n in g["nodes"] if n["mode"] == 4) == {1, 2, 4, 5}
assert [8, 11, 0, 10, 4, "FLOAT"] in g["links"] and [14, 8, 2, 10, 1, "AUDIO"] in g["links"]
assert "mode4" in b["user_overview"] and "音频来自素材8" in b["user_overview"]
assert not b["counts"]["final_prompt_constructed"]
for n in (4, 9):
f = next(
f for f in b["fields"] if f["node_id"] == str(n) and f["field"] == "saved_position_3"
)
assert f["value"] is None and f["role"] == "frontend_state_unknown"
rate = next(f for f in b["fields"] if f["field"] == "frame_rate")
assert rate["value"] == 8 and "覆盖8" in rate["effect"]
assert "-shortest" in next(f["effect"] for f in b["fields"] if f["field"] == "trim_to_audio")