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

231 lines
8.7 KiB
Python

"""Interpolation comparison source identity, inactive lengths and fail-closed bindings."""
import ast
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/resize-compare-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=SOURCE, review=REVIEW):
return build_document(PATH, source, None, None, [], 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_position_type_scope_citations_and_no_fabricated_named_values(f):
assert canonical(pointer(SOURCE, f["pointer"])) == canonical(f["value"])
assert type(pointer(SOURCE, f["pointer"])).__name__ == f["json_type"]
assert f["scope"] == "root" and "named_value" not in f and "named_pointer" not in f
for key in [
"effect",
"label",
"schema_default",
"unit",
"limits",
"execution_note",
"role",
"type",
]:
assert f[key]
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", ["value", "text"])
def test_each_position_or_description_forgery_refused(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:
parent, _, key = f["pointer"].rpartition("/")
pointer(s, parent)[int(key)] = "forged"
refuse(s, r)
@pytest.mark.parametrize("i", range(17))
@pytest.mark.parametrize("variant", ["mode", "identity"])
def test_each_node_state_and_identity_is_bound(i, variant):
s, r = copy.deepcopy(SOURCE), copy.deepcopy(REVIEW)
if variant == "mode":
s["nodes"][i]["mode"] = 2
else:
s["nodes"][i]["properties"]["ver"] = "forged"
refuse(s, r)
@pytest.mark.parametrize("i", range(20))
@pytest.mark.parametrize("variant", ["record", "input", "output"])
def test_all_physical_endpoints_bound(i, variant):
s, r = copy.deepcopy(SOURCE), copy.deepcopy(REVIEW)
eid, src, slot, dst, inp, _ = s["links"][i]
ns = {n["id"]: n for n in s["nodes"]}
if variant == "record":
s["links"][i][3] = 99999
elif variant == "input":
ns[dst]["inputs"][inp]["link"] = 99999
else:
ns[src]["outputs"][slot]["links"] = []
refuse(s, r)
@pytest.mark.parametrize(
"variant",
[
"named",
"frontend",
"mask",
"ue",
"empty_preview",
"missing",
"empty",
"path",
"source_sha",
"citation",
"overview",
],
)
def test_special_boundaries_cannot_be_retrusted(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 == "named":
ns[2]["widgets_values_named"] = {"width": 480}
elif variant == "frontend":
s["extra"]["frontendVersion"] = "1.45.20"
elif variant == "mask":
ns[2]["outputs"].pop()
elif variant == "ue":
ns[2]["properties"]["ue_properties"]["version"] = "7.8"
elif variant == "empty_preview":
ns[3]["widgets_values"] = None
elif variant in ["missing", "empty"]:
r["fixed_version_document"] = {} if variant == "empty" else None
assert not doc(s, r)["fixed_version"]["matched"]
return
elif variant == "path":
b["source_path"] = "wrong"
elif variant == "source_sha":
r["source_sha"] = "wrong"
elif variant == "citation":
b["sources"][0]["sha256"] = "wrong"
else:
b["user_overview"] = "wrong"
refuse(s, r)
def test_independent_inventory_links_overrides_and_zero_nodes():
assert doc()["fixed_version"]["matched"]
assert len(SOURCE["nodes"]) == 17 and len(SOURCE["links"]) == 20 and "definitions" not in SOURCE
expected = [
f"/nodes/{i}/widgets_values/{j}"
for i, n in enumerate(SOURCE["nodes"])
for j in range(len(n["widgets_values"]))
]
assert expected == [f["pointer"] for f in BLOCK["fields"]] and len(expected) == 35
ns = {n["id"]: n for n in SOURCE["nodes"]}
for eid, src, slot, dst, inp, typ in SOURCE["links"]:
assert ns[dst]["inputs"][inp]["link"] == eid
assert eid in ns[src]["outputs"][slot]["links"]
assert ns[src]["outputs"][slot]["type"] == typ or typ == "*"
assert [
(e[1], e[3], ns[e[3]]["inputs"][e[4]]["name"]) for e in SOURCE["links"] if e[1] in [11, 12]
] == [
(11, 2, "width"),
(12, 2, "height"),
(12, 4, "height"),
(12, 5, "scale_by_length"),
(12, 7, "scale_to_length"),
(11, 4, "width"),
]
assert [n["node_id"] for n in BLOCK["zero_saved_nodes"]] == ["3", "8", "9", "10"]
assert sum(f["value"] == "" for f in BLOCK["fields"]) == 6 and not BLOCK["comments"]
assert all(n["mode"] == 0 and "widgets_values_named" not in n for n in SOURCE["nodes"])
assert ns[1]["outputs"][1]["links"] is None
def test_precise_static_branch_conditions_and_interface_conflict_without_execution():
ref = OUT.parent / "resize-compare-reference"
kj = (ref / "kj__nodes__image_nodes.py").read_text()
tree = ast.parse(kj)
node = next(x for x in tree.body if isinstance(x, ast.ClassDef) and x.name == "ImageResizeKJv2")
return_types = next(
x.value
for x in node.body
if isinstance(x, ast.Assign)
and any(isinstance(t, ast.Name) and t.id == "RETURN_TYPES" for t in x.targets)
)
assert ast.literal_eval(return_types) == ("IMAGE", "INT", "INT")
resize = next(x for x in node.body if isinstance(x, ast.FunctionDef) and x.name == "resize")
assert "mask" not in [x.arg for x in resize.args.args]
assert "width = width - (width % divisible_by)" in kj
restore = (ref / "layer__py__image_scale_restore_v2.py").read_text()
assert "if original_size is not None:" in restore and "if scale_by == 'longest':" in restore
assert (
"target_width = int(orig_width * scale)" in restore
and "if scale_by == 'by_scale':" not in restore
)
aspect = (ref / "layer__py__image_scale_by_aspect_ratio_v2.py").read_text()
assert "elif scale_to_side == 'total_pixel(kilo pixel)':" in aspect
assert "target_width = orig_width" in aspect and "if round_to_multiple != 'None':" in aspect
preview = (ref / "core__nodes.py").read_text()
assert "RETURN_TYPES = ()" in preview and "class PreviewImage(SaveImage)" in preview
fields = {(f["node_id"], f["field"]): f for f in BLOCK["fields"]}
assert fields["5", "scale"]["json_type"] == "int" and fields["5", "scale"]["type"] == "FLOAT"
assert fields["7", "round_to_multiple"]["value"] == "8"
assert all(
"不" in fields[n, k]["effect"]
for n, k in [("5", "scale_by_length"), ("7", "scale_to_length")]
)
def test_old_33_blocks_and_all_other_reviews_frozen():
p = "calliope-backend/src/calliope/comfyui/source_reviews.json"
old = json.loads(subprocess.check_output(["git", "show", "ce9502a:" + p], cwd=REPO))
now = json.loads((REPO / p).read_bytes())
now[PATH].pop("fixed_version_document")
assert now == old and len(DEFINITIONS) == 34
blocks = [r["fixed_version_document"] for r in old.values() if "fixed_version_document" in r]
assert (
len(blocks) == 33
and sum(len(b["fields"]) for b in blocks) == 1034
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
)
== 25
)