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

224 lines
8.9 KiB
Python

"Flux2 editorial source binding, distinct saved states and unchanged eligibility."
import copy
import hashlib
import json
import runpy
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/flux2-views-document-evidence")
PATH = "example_ComfyUI_workflows/3-图像生成/Flux/10_flux2_klein_文生图-角色三视图.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 part in p.strip("/").split("/"):
obj = obj[int(part)] if isinstance(obj, list) else obj[part]
return obj
def doc(s=SOURCE, r=REVIEW):
return build_document(PATH, s, None, None, [], r)
def refuse(s, r):
r["fixed_version_document"]["canonical_sha256"] = hashlib.sha256(canonical(s)).hexdigest()
assert not doc(s, r)["fixed_version"]["matched"]
def test_exact_source_and_no_qualification_change():
b = runpy.run_path(str(OUT / "build_definition.py"))["build"]()
assert canonical(b) == canonical(BLOCK)
assert len(DEFINITIONS) == 55
assert len(b["fields"]) == 48 and len(b["comments"]) == 1
assert b["counts"]["linked_saved_fields"] == 6
assert b["counts"]["frontend_only"] == 2
assert doc()["fixed_version"]["matched"]
assert not doc()["status"]["doc_done"] and not doc()["status"]["exec_verified"]
ns = {n["id"]: n for n in SOURCE["nodes"]}
assert b["comments"][0]["text"] == ns[93]["widgets_values"][0]
assert len(b["comments"][0]["text"]) == 568
assert {s["id"] for s in b["sources"]} == {
"core",
"lora",
"frontend",
"tt",
"easy",
"cr",
"showtext",
"llama",
}
assert {s["tag"] for s in b["sources"] if s["id"] == "frontend"} == {"v1.36.14"}
assert {s["commit"] for s in b["sources"] if s["id"] == "easy"} == {
"81c510c06e18dffd4f43518644fc35964c9168ca"
}
def test_physical_active_list_and_disconnected_language_branch():
edges = {tuple(e[1:]) for e in SOURCE["links"]}
assert (97, 1, 88, 1, "STRING") in edges
assert (96, 0, 99, 5, "STRING") in edges
assert (100, 0, 99, 0, "LLAMACPPMODEL") in edges
assert (99, 0, 95, 0, "STRING") in edges
assert not any(e[0] in [95, 96, 99, 100] and e[2] in [97, 88] for e in edges)
ns = {n["id"]: n for n in SOURCE["nodes"]}
assert {n["id"] for n in SOURCE["nodes"] if n["mode"] == 4} == {95, 96, 99, 100, 104}
assert ns[97]["outputs"][0]["links"] is None
assert ns[97]["outputs"][1]["type"] == "STRING"
assert ns[97]["outputs"][1]["shape"] == 6
assert ns[97]["inputs"][0]["link"] is None
assert ns[97]["widgets_values"][-2:] == ["", ""]
f = {(f["node_id"], f["field"]): f for f in BLOCK["fields"]}
for nid, key in [(88, "text"), (99, "custom_prompt")]:
assert f[str(nid), key]["value"] == ""
assert f[str(nid), key]["role"] == "linked_saved_cache"
assert f["81", "cfg"]["value"] == 1 and f["81", "cfg"]["json_type"] == "int"
assert f["101", "use_custom_resolution"]["value"] is False
assert ns[82]["outputs"][1]["links"] == [] and ns[9]["outputs"] == []
for e in [
(101, 0, 102, 0, "INT"),
(101, 1, 103, 0, "INT"),
(102, 0, 80, 1, "INT"),
(102, 0, 84, 0, "INT"),
(103, 0, 80, 2, "INT"),
(103, 0, 84, 1, "INT"),
(84, 0, 82, 4, "LATENT"),
(82, 0, 83, 0, "LATENT"),
(83, 0, 9, 0, "IMAGE"),
(89, 0, 104, 0, "MODEL"),
(104, 0, 81, 0, "MODEL"),
]:
assert e in edges
assert len(f["96", "text"]["value"]) > 1000
assert "Role:" in f["99", "system_prompt"]["value"]
assert {x["node_id"]: x["state"] for x in BLOCK["zero_saved_nodes"]} == {
"83": "empty_list",
"82": "empty_list",
"95": "empty_list",
"102": "missing",
"103": "missing",
}
def test_passive_list_and_state_conditions_against_exact_text():
def read(key, file):
e = next(e for e in BLOCK["sources"] if e["id"] == key and e["file"] == file)
return (OUT / e["local_file"]).read_text()
easy = read("easy", "py/nodes/prompt.py")
assert 'io.String.Output("prompt_strings", is_output_list=True)' in easy
assert "if optional_prompt_list:" in easy
assert "if isinstance(p, str) and p != '':" in easy
assert "return io.NodeOutput(prompts, prompts)" in easy
io = read("core", "comfy_api/latest/_io.py")
assert "output_is_list.append(o.is_output_list)" in io
assert "cls._RETURN_TYPES = output" in io and "cls._OUTPUT_IS_LIST = output_is_list" in io
execution = read("core", "execution.py")
assert "v[i if len(v) > i else -1]" in execution and "value.extend(o[i])" in execution
llama = read("llama", "nodes.py")
assert "if parameters is None:" in llama and '"max_tokens": 1024' in llama
assert 'if custom_prompt.strip() and "*" not in preset_prompt:' in llama
assert "LLAMA_CPP_STORAGE.llm._ctx.memory_clear(True)" in llama
assert "if save_states:" in llama and "if force_offload:" in llama
lora = read("lora", "nodes.py")
assert "if strength_model == 0 and strength_clip == 0:" in lora
assert "self.load_lora(model, None, lora_name, strength_model, 0)[0]" in lora
tt = read("tt", "nodes/resolution_selector.py")
assert "self.RESOLUTIONS.get(resolution, (1024, 1024))" in tt
@pytest.mark.parametrize("f", BLOCK["fields"], ids=lambda f: f["node_id"] + "." + f["field"])
def test_every_saved_position_json_type_and_exact_citations(f):
assert canonical(pointer(SOURCE, f["pointer"])) == canonical(f["value"])
assert type(pointer(SOURCE, f["pointer"])).__name__ == f["json_type"]
assert "named_value" not in f and "无widgets_values_named" in f["named_pointer"]
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", ["position", "editorial"])
def test_caller_rehash_cannot_expand_trust(f, variant):
s, r = copy.deepcopy(SOURCE), copy.deepcopy(REVIEW)
if variant == "editorial":
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("index", range(23))
@pytest.mark.parametrize("variant", ["mode", "identity", "named"])
def test_all_nodes_bound(index, variant):
s, r = copy.deepcopy(SOURCE), copy.deepcopy(REVIEW)
n = s["nodes"][index]
if variant == "mode":
n["mode"] = 0 if n["mode"] == 4 else 4
elif variant == "identity":
n["properties"]["ver"] = "forged"
else:
n["widgets_values_named"] = {"forged": 0}
refuse(s, r)
@pytest.mark.parametrize("index", range(24))
def test_all_edges_bound(index):
s, r = copy.deepcopy(SOURCE), copy.deepcopy(REVIEW)
s["links"][index][3] = 9999
refuse(s, r)
@pytest.mark.parametrize("node", [83, 82, 95, 102, 103])
@pytest.mark.parametrize("variant", ["missing", "empty", "null", "added"])
def test_missing_empty_null_distinct(node, variant):
s, r = copy.deepcopy(SOURCE), copy.deepcopy(REVIEW)
n = next(n for n in s["nodes"] if n["id"] == node)
old = copy.deepcopy(n)
if variant == "missing":
n.pop("widgets_values", None)
else:
n["widgets_values"] = {"empty": [], "null": None, "added": [0]}[variant]
if n != old:
refuse(s, r)
@pytest.mark.parametrize(
"variant",
["overview", "citation", "sha", "frontend", "counts", "tab", "ue", "unconnected-output"],
)
def test_metadata_and_unconnected_branch_bound(variant):
s, r = copy.deepcopy(SOURCE), copy.deepcopy(REVIEW)
b = r["fixed_version_document"]
if variant == "overview":
b["user_overview"] = "forged"
elif variant == "citation":
b["sources"][0]["sha256"] = "forged"
elif variant == "sha":
r["source_sha"] = "forged"
elif variant == "frontend":
s["extra"]["frontendVersion"] = "1.52.7"
elif variant == "counts":
b["counts"]["final_prompt_constructed"] = True
elif variant == "tab":
s["nodes"][0]["properties"]["tabWidth"] = 99
elif variant == "ue":
s["nodes"][0]["properties"]["ue_properties"]["version"] = "7.8"
else:
next(n for n in s["nodes"] if n["id"] == 82)["outputs"][1]["links"] = [999]
assert not doc(s, r)["fixed_version"]["matched"]