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

217 lines
9.1 KiB
Python

"Exact graph binding, all saved positions, dual scopes and closed eligibility."
import ast
import copy
import hashlib
import json
import runpy
import sys
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/zimage-wash-document-evidence"
PATH = "example_ComfyUI_workflows/3-图像生成/Z-Image/8_Z-image+Controlnet_姿势控制-洗图.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, p):
for x in p.strip("/").split("/"):
obj = obj[int(x)] if isinstance(obj, list) else obj[x]
return obj
def doc(s=SOURCE, r=REVIEW):
return build_document(PATH, s, None, None, [], r)
@pytest.mark.parametrize("f", BLOCK["fields"], ids=lambda f: f["node_id"] + "." + f["field"])
def test_each_saved_position_and_citation(f):
assert canonical(pointer(SOURCE, f["pointer"])) == canonical(f["value"])
assert type(pointer(SOURCE, f["pointer"])).__name__ == f["json_type"]
assert "无widgets_values_named" in f["named_pointer"] and "named_value" not in f
assert all(
f[k] for k in ["label", "unit", "limits", "schema_default", "effect", "execution_note"]
)
if f["input_pointer"].startswith("/"):
assert pointer(SOURCE, f["input_pointer"])["name"] == f["input_name"]
for i in f["evidence"]:
e = BLOCK["sources"][i]
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())
@pytest.mark.parametrize("f", BLOCK["fields"], ids=lambda f: f["node_id"] + "." + f["field"])
@pytest.mark.parametrize("variant", ["source", "text"])
def test_caller_rehash_cannot_expand_trust(f, variant):
s, r = copy.deepcopy(SOURCE), copy.deepcopy(REVIEW)
if variant == "text":
r["fixed_version_document"]["fields"][BLOCK["fields"].index(f)]["effect"] = "forged"
else:
p, _, key = f["pointer"].rpartition("/")
pointer(s, p)[int(key)] = "forged"
r["fixed_version_document"]["canonical_sha256"] = hashlib.sha256(canonical(s)).hexdigest()
assert not doc(s, r)["fixed_version"]["matched"]
@pytest.mark.parametrize("key", ["extra", "links", "id", "groups", "version"])
def test_whole_graph_mutations_fail_closed(key):
source, review = copy.deepcopy(SOURCE), copy.deepcopy(REVIEW)
source[key] = "forged"
review["fixed_version_document"]["canonical_sha256"] = hashlib.sha256(
canonical(source)
).hexdigest()
assert not doc(source, review)["fixed_version"]["matched"]
@pytest.mark.parametrize("key", ["mode", "properties", "inputs", "outputs"])
@pytest.mark.parametrize("index", [0, 4, 12, 15])
def test_node_identity_and_state_fail_closed(key, index):
source, review = copy.deepcopy(SOURCE), copy.deepcopy(REVIEW)
source["nodes"][index][key] = "forged"
review["fixed_version_document"]["canonical_sha256"] = hashlib.sha256(
canonical(source)
).hexdigest()
assert not doc(source, review)["fixed_version"]["matched"]
def test_exact_build_and_qualification():
assert canonical(runpy.run_path(str(OUT / "build_definition.py"))["build"]()) == canonical(
BLOCK
)
assert len(DEFINITIONS) == 68 and doc()["fixed_version"]["matched"]
assert BLOCK["counts"]["saved_fields"] == BLOCK["counts"]["root_saved_fields"] == 138
assert BLOCK["counts"]["source_notes"] == 1 and len(BLOCK["comments"]) == 1
assert not doc()["status"]["doc_done"] and not doc()["status"]["exec_verified"]
sys.path.insert(0, str(OUT))
try:
runpy.run_path(str(OUT / "verify_sources.py"))["main"]()
finally:
sys.path.remove(str(OUT))
def test_exact_wash_graph_and_identity_gaps():
ns = {n["id"]: n for n in SOURCE["nodes"]}
assert sum(n["mode"] == 4 for n in SOURCE["nodes"]) == 10
assert ns[143]["outputs"][1]["links"] == []
assert ns[303]["widgets_values"] == ["DepthAnythingPreprocessor", 1024]
assert ns[321]["widgets_values"][6:8] == ["total_pixel(kilo pixel)", 2048]
assert ns[675]["inputs"][0]["link"] == 3406 and ns[675]["inputs"][1]["link"] == 3407
assert ns[313]["inputs"][0]["link"] == 3270 and ns[314]["inputs"][0]["link"] == 3130
assert ns[313]["inputs"][3]["link"] == 3408 and ns[314]["inputs"][3]["link"] == 2687
assert ns[313]["inputs"][5]["link"] == 3097 and ns[314]["inputs"][5]["link"] == 3112
assert ns[618]["widgets_values"] == [9528, "fixed", None]
assert not any(n["type"] in ["VAEEncode", "SetLatentNoiseMask"] for n in SOURCE["nodes"])
assert "ver" not in ns[679]["properties"] and "cnr_id" not in ns[679]["properties"]
assert ns[231]["inputs"][1]["link"] == 2067 and ns[230]["widgets_values"] == ["SeedVR 修复"]
flow = "\n".join(BLOCK["flow"])
for word in [
"DepthAnythingPreprocessor",
"不是已选姿态",
"只有第一段接ControlNet",
"9528/fixed/null",
"Exposure679没有cnr_id/ver",
"SeedVR 修复",
"362字",
"0.5.1",
]:
assert word in flow or word in BLOCK["user_overview"]
for f in BLOCK["fields"]:
if f["node_id"] == "629":
assert f["input_name"] is None
if f["node_id"] == "679":
assert all("未知" in f[k] for k in ["schema_default", "limits", "unit"])
linked = {
f["node_id"] + "." + f["field"]
for f in BLOCK["fields"]
if f["input_pointer"].startswith("/")
and pointer(SOURCE, f["input_pointer"]).get("link") is not None
}
assert linked == {"675.width", "675.height", "313.noise_seed", "314.noise_seed", "300.text"}
@pytest.mark.parametrize("note", BLOCK["comments"])
def test_full_notes_and_note_forgery(note):
assert pointer(SOURCE, note["pointer"]) == note["text"]
source, review = copy.deepcopy(SOURCE), copy.deepcopy(REVIEW)
review["fixed_version_document"]["comments"][0]["text"] = "forged"
assert not doc(source, review)["fixed_version"]["matched"]
def test_path_and_source_binding_cannot_be_extended():
from calliope.comfyui.fixed_document import fixed_document_for
assert fixed_document_for(PATH + "forged", SOURCE, REVIEW) is None
review = copy.deepcopy(REVIEW)
review["source_sha"] = "forged"
assert not doc(SOURCE, review)["fixed_version"]["matched"]
@pytest.mark.parametrize("suffix", [b"\n", b" ", b"\t"])
def test_original_byte_identity_rejects_equivalent_json(suffix):
altered = RAW + suffix
assert json.loads(altered) == SOURCE
assert review_for(PATH, hashlib.sha1(altered).hexdigest()) is None
@pytest.mark.parametrize("key", ["user_overview", "source_sha256", "sources", "flow", "counts"])
def test_editorial_or_citation_rehash_cannot_replace_code_owned_pin(key):
source, review = copy.deepcopy(SOURCE), copy.deepcopy(REVIEW)
review["fixed_version_document"][key] = "forged"
review["fixed_version_document"]["canonical_sha256"] = hashlib.sha256(
canonical(source)
).hexdigest()
assert not doc(source, review)["fixed_version"]["matched"]
@pytest.mark.parametrize(
"nid,key",
[(295, "core0375"), (234, "core0367"), (322, "core0376"), (617, "core051"), (233, "core0359")],
)
def test_exact_declared_output_and_empty_backend_return(nid, key):
n = next(n for n in SOURCE["nodes"] if n["id"] == nid)
assert n["outputs"] == [{"name": "image_urls", "type": "STRING"}]
if n["type"] == "PreviewImage":
assert n["widgets_values"] == []
e = next(e for e in BLOCK["sources"] if e["id"] == key and e["file"] == "nodes.py")
tree = ast.parse((OUT / e["local_file"]).read_bytes())
save = next(c for c in tree.body if isinstance(c, ast.ClassDef) and c.name == "SaveImage")
ret = next(
c.value
for c in save.body
if isinstance(c, ast.Assign)
and any(isinstance(t, ast.Name) and t.id == "RETURN_TYPES" for t in c.targets)
)
assert isinstance(ret, ast.Tuple) and ret.elts == []
if n["type"] == "PreviewImage":
c = next(c for c in tree.body if isinstance(c, ast.ClassDef) and c.name == "PreviewImage")
assert [ast.unparse(b) for b in c.bases] == ["SaveImage"]
effect = next(
z["effect"]
for z in doc()["fixed_version"]["zero_saved_nodes"]
if z["node_id"] == str(nid)
)
else:
effect = next(
f["effect"] for f in doc()["fixed_version"]["fields"] if f["node_id"] == str(nid)
)
assert "源声明STRING" in effect and "接口差异" in effect
def test_easy_seed_null_and_model_identity_are_not_normalized():
f = next(f for f in BLOCK["fields"] if f["node_id"] == "618" and f["field"] == "saved_aux_null")
assert f["value"] is None and f["json_type"] == "NoneType" and f["input_name"] is None
assert "未知" in f["schema_default"]
dit = next(
f for f in BLOCK["fields"] if f["node_id"] == "629" and f["field"] == "saved_position_0"
)
assert dit["value"] == "seedvr2_ema_3b_fp8_e4m3fn.safetensors"