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

302 lines
11 KiB
Python

"""Exact SDPose source binding, real document output, old definitions and refusal regressions."""
from __future__ import annotations
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/sdpose-document-evidence"
PATH = next(p for p in DEFINITIONS if p.endswith("sdpose_视频人物姿势骨架提取.json"))
RAW = (REPO / PATH).read_bytes()
SOURCE = json.loads(RAW)
REVIEW = review_for(PATH, hashlib.sha1(RAW).hexdigest())
BLOCK = REVIEW["fixed_version_document"]
def pointer(obj, path):
for part in path.strip("/").split("/"):
part = part.replace("~1", "/").replace("~0", "~")
obj = obj[int(part)] if isinstance(obj, list) else obj[part]
return obj
def doc(source=None, review=None, path=PATH):
return build_document(
path,
SOURCE if source is None else source,
None,
None,
[],
REVIEW if review is None else review,
)
@pytest.mark.parametrize("field", BLOCK["fields"], ids=lambda f: f["node_id"] + "." + f["field"])
def test_saved_values_types_and_fixed_citations(field):
v = pointer(SOURCE, field["pointer"])
assert canonical(v) == canonical(field["value"]) and type(v).__name__ == field["json_type"]
node = pointer(SOURCE, field["pointer"].split("/widgets_values/")[0])
assert str(node["id"]) == field["node_id"] and node["type"] == field["class_type"]
assert node["properties"]["ver"] in ["0.15.0", "0.15.1"]
for k in ["label", "schema_default", "unit", "limits", "effect", "execution_note"]:
assert field[k]
for k in field["evidence"]:
e = BLOCK["sources"][k]
raw = (OUT / e["local_file"]).read_bytes()
assert hashlib.sha256(raw).hexdigest() == e["sha256"]
assert len(e["commit"]) == 40 and e["commit"] in e["url"]
assert 1 <= e["lines"][0] <= e["lines"][1] <= len(raw.decode().splitlines())
@pytest.mark.parametrize("index", range(18))
@pytest.mark.parametrize("kind", ["value", "type", "pointer", "citation", "role", "default"])
def test_forged_fields_fail_even_after_caller_digest_recalculation(index, kind):
source, review = copy.deepcopy(SOURCE), copy.deepcopy(REVIEW)
b = review["fixed_version_document"]
f = b["fields"][index]
if kind in ["value", "type"]:
parent, _, key = f["pointer"].rpartition("/")
pointer(source, parent)[int(key)] = (
{"forged": True} if kind == "value" else (1 if isinstance(f["value"], bool) else False)
)
# Even when source and editorial field are forged consistently, trust cannot expand.
f["value"] = pointer(source, f["pointer"])
f["json_type"] = type(f["value"]).__name__
elif kind == "citation":
b["sources"][f["evidence"][0]]["sha256"] = "0" * 64
else:
f[{"default": "schema_default"}.get(kind, kind)] = "forged"
b["canonical_sha256"] = hashlib.sha256(canonical(source)).hexdigest()
review["caller_digest"] = hashlib.sha256(canonical(b)).hexdigest()
actual = doc(source, review)["fixed_version"]
assert actual["matched"] is False and "fields" not in actual
MUTATIONS = (
[
"/links/0/1",
"/links/9/2",
"/extra/frontendVersion",
"/extra/comfy_fork_version",
"/extra/prompt",
"/nodes/4/widgets_values/0",
"/nodes/5/properties/models/0/url",
"/nodes/8/properties/ue_properties/widget_ue_connectable/fps",
]
+ [
f"/nodes/{i}/{suffix}"
for i in range(9)
for suffix in ["mode", "type", "properties/ue_properties/version"]
]
+ [
f"/nodes/{i}/properties/{key}"
for i in [0, 1, 2, 3, 5, 6, 7, 8]
for key in ["cnr_id", "ver"]
]
)
@pytest.mark.parametrize("path", MUTATIONS)
def test_versions_providers_modes_edges_notes_and_model_metadata_fail_closed(path):
source, review = copy.deepcopy(SOURCE), copy.deepcopy(REVIEW)
parent, _, key = path.rpartition("/")
target = pointer(source, parent)
target[int(key) if isinstance(target, list) else key] = "forged"
review["fixed_version_document"]["canonical_sha256"] = hashlib.sha256(
canonical(source)
).hexdigest()
review["caller_digest"] = hashlib.sha256(
canonical(review["fixed_version_document"])
).hexdigest()
assert not doc(source, review)["fixed_version"]["matched"]
@pytest.mark.parametrize(
"key",
[
"source_path",
"source_sha1",
"source_sha256",
"notice",
"user_overview",
"versions",
"comments",
"flow",
"sources",
],
)
def test_editorial_and_identity_forgery_rejected(key):
review = copy.deepcopy(REVIEW)
review["fixed_version_document"][key] = "forged"
review["caller_digest"] = hashlib.sha256(
canonical(review["fixed_version_document"])
).hexdigest()
assert not doc(review=review)["fixed_version"]["matched"]
def test_real_document_and_frozen_old_fourteen_blocks():
d = doc()
assert d["fixed_version"]["matched"] and d["fixed_version"]["fields"] == BLOCK["fields"]
assert d["status"] == dict(imported=True, doc_done=False, exec_verified=False)
assert d["dependencies"]["check_state"] == "unchecked"
assert "fixed_version" not in doc(path="untrusted.json")
review = copy.deepcopy(REVIEW)
other = next(
p
for p in DEFINITIONS
if p != PATH
and not p.endswith("/多视频合成分屏展示.json")
and not p.endswith("/图像4种添加水印节点.json")
and not p.endswith("/birefnet_图像移除背景.json")
and not p.endswith(("/截取视频每一帧.json", "/加载本地latent解码.json"))
and not p.endswith(
("NLF_视频人物动作骨架获取.json", "/视频倒放.json", "双图像或视频合并显示.json")
)
)
resource = "calliope-backend/src/calliope/comfyui/source_reviews.json"
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")
for added in [
p
for p in now
if p.endswith(
(
"视频转gif动图图片.json",
"加载图片合成视频.json",
"双图像或视频合并显示.json",
)
)
]:
now[added].pop("fixed_version_document")
reverse = next(p for p in now if p.endswith("/视频倒放.json"))
now[reverse].pop("fixed_version_document")
nlf = next(p for p in now if p.endswith("NLF_视频人物动作骨架获取.json"))
now[nlf].pop("fixed_version_document")
openpose = next(p for p in now if p.endswith("openpose-video-姿态检测.json"))
review["fixed_version_document"] = now[other]["fixed_version_document"]
assert not doc(review=review)["fixed_version"]["matched"]
now[openpose].pop("fixed_version_document")
old = json.loads(subprocess.check_output(["git", "show", "7291887:" + resource], cwd=REPO))
assert len(now) == 156 and len(DEFINITIONS) == 26
old_blocks = [
r["fixed_version_document"] for r in old.values() if "fixed_version_document" in r
]
assert len(old_blocks) == 14
assert sum(len(b["fields"]) for b in old_blocks) == 376
assert (
sum(len(b.get("comments", [])) for b in old_blocks) == 12
) # ASR history includes flow note.
assert now[PATH].pop("fixed_version_document") == BLOCK
assert now == old
def test_exact_topology_nulls_conditions_and_reference_identity():
assert BLOCK["source_sha256"] == hashlib.sha256(RAW).hexdigest()
assert BLOCK["canonical_sha256"] == hashlib.sha256(canonical(SOURCE)).hexdigest()
assert len(SOURCE["nodes"]) == 9 and len(SOURCE["links"]) == 10
assert [e[0] for e in SOURCE["links"]] == [
1725,
1732,
1733,
1734,
1735,
1736,
1737,
1738,
1739,
1740,
]
assert SOURCE["links"][-2:] == [
[1739, 685, 1, 681, 1, "AUDIO"],
[1740, 685, 2, 681, 2, "FLOAT"],
]
assert all(n["mode"] == 0 for n in SOURCE["nodes"])
assert len(BLOCK["fields"]) == 18 and len(BLOCK["comments"]) == 1
assert sum(f["role"] == "source_named_unconfirmed" for f in BLOCK["fields"]) == 8
assert sum(f["role"] == "linked_saved" for f in BLOCK["fields"]) == 1
for n in BLOCK["comments"]:
assert pointer(SOURCE, n["pointer"]) == n["text"]
assert "widgets_values" not in SOURCE["nodes"][2]
assert SOURCE["nodes"][2].get("widgets_values") is None
assert BLOCK["zero_saved_nodes"][0]["node_id"] == "685"
fields = {(f["node_id"], f["field"]): f for f in BLOCK["fields"]}
assert fields["681", "fps"]["value"] == 30 and fields["681", "fps"]["json_type"] == "int"
assert fields["683", "resize_type.longer_size"]["value"] == 1024
assert [f["value"] for f in BLOCK["fields"] if f["node_id"] == "686"] == [
True,
True,
True,
True,
4,
2,
0.5,
]
assert {e["commit"] for e in BLOCK["sources"]} == {
"b874bd2b8c324d58cfc37bff0754dd16815a8f3c",
"3dd10a59c00248d00f0cb0ab794ff1bb9fb00a5f",
"d91c283b7b758787b4d29126c1a9ac39dc14d6a7",
}
assert all(
t in "".join(BLOCK["flow"])
for t in [
"外线覆盖",
"未知",
"不同流程缓存",
"未找到",
"UE7.7.1",
"没有widgets_values键",
"bboxes",
"不产prompt",
]
)
assert not BLOCK["counts"]["final_prompt_constructed"]
@pytest.mark.parametrize("missing_value", [None, []])
def test_absent_widgets_key_cannot_be_replaced_by_null_or_empty_list(missing_value):
source = copy.deepcopy(SOURCE)
source["nodes"][2]["widgets_values"] = missing_value
assert not doc(source=source)["fixed_version"]["matched"]
def test_wrong_raw_source_sha_cannot_receive_fixed_reference():
assert review_for(PATH, "0" * 40) is None
review = copy.deepcopy(REVIEW)
review["source_sha"] = "0" * 40
assert not doc(review=review)["fixed_version"]["matched"]
def test_missing_packages_give_chinese_build_hint(tmp_path):
import sys
code = (
"import runpy,sys; from pathlib import Path; "
"ns=runpy.run_path('recompute.py'); "
"ns['require_packages'].__globals__['REPO']=Path(sys.argv[1]); "
"ns['require_packages']()"
)
result = subprocess.run(
[sys.executable, "-c", code, str(tmp_path)], cwd=OUT, capture_output=True, text=True
)
assert result.returncode != 0
assert "缺少wheel/sdist包产物" in result.stderr
assert "uv build --project calliope-backend --offline" in result.stderr