Files
aigc-home/calliope-backend/tests/test_output_protocol_references.py
T
2026-10-29 22:51:08 +08:00

213 lines
8.5 KiB
Python

"""Public-source contract fixtures, never target history or real generation evidence."""
from __future__ import annotations
import copy
import json
from pathlib import Path
import httpx
import pytest
from calliope.comfyui.client import ComfyUIClient
from calliope.comfyui.companions import load_companions, resolve_companion
from calliope.comfyui.library import import_library
from calliope.comfyui.output_map import auto_output_map
from calliope.comfyui.protocol_references import companion_protocol_reference
from calliope.db import get_db, migrate_db
REPO = Path(__file__).resolve().parents[2]
MANIFEST = REPO / "docs/hel-892/supplied-api/manifest.json"
ROOT = REPO / "example_ComfyUI_workflows"
FIXTURE = json.loads((REPO / "docs/hel-892/protocol-evidence/serialization.json").read_text())
async def test_core_audio_contract_reuses_download_path(tmp_path):
client = ComfyUIClient("http://source-contract.invalid")
await client._http.aclose()
requests = []
def view(request):
requests.append(request)
assert request.url.path == "/view"
assert dict(request.url.params) == {
"filename": "music_00001.mp3",
"subfolder": "audio",
"type": "output",
}
return httpx.Response(200, content=b"contract transport fixture, not encoded audio")
client._http = httpx.AsyncClient(transport=httpx.MockTransport(view))
try:
items = client.extract_outputs(FIXTURE["audio_history_fixture"], {"35": "audio"})
assert items == [
{
"filename": "music_00001.mp3",
"subfolder": "audio",
"type": "output",
"node_id": "35",
"media_kind": "audio",
}
]
item = items[0]
dest = tmp_path / item["filename"]
await client.download_image(item["filename"], item["subfolder"], item["type"], dest)
assert dest.read_bytes() == b"contract transport fixture, not encoded audio"
assert len(requests) == 1
finally:
await client.close()
async def test_inline_text_and_paths_never_become_files():
client = ComfyUIClient()
try:
assert FIXTURE["target_history_observed"] is False
assert client.extract_outputs(FIXTURE["subtitle_history_fixture"]) == []
assert (
client.extract_outputs(
{
"outputs": {
"1": {
"text": ["1\n00:00:00,000 --> 00:00:01,000\n字幕", "/output/test.srt"],
"files": ["test.srt", {"text": "字幕"}],
"mystery": [{"filename": "unknown.mp3"}],
}
}
}
)
== []
)
finally:
await client.close()
@pytest.mark.parametrize(
"item",
[
{},
{"filename": ""},
{"filename": 42},
{"filename": ["music.mp3"]},
{"filename": "https://elsewhere/music.mp3"},
{"filename": "../music.mp3"},
{"filename": "..\\music.mp3"},
{"filename": "."},
{"filename": "music.mp3", "subfolder": None},
{"filename": "music.mp3", "subfolder": "../../elsewhere"},
{"filename": "music.mp3", "subfolder": "/tmp"},
{"filename": "music.mp3", "type": "url"},
],
)
async def test_invalid_descriptors_not_collected(item):
client = ComfyUIClient()
try:
assert client.extract_outputs({"outputs": {"35": {"audio": [item]}}}) == []
finally:
await client.close()
async def test_file_audio_and_node_scope_contracts():
client = ComfyUIClient()
try:
history = {
"outputs": {
"subtitle": {
"files": [{"filename": "字幕.srt", "subfolder": "", "type": "output"}]
},
"music": {"audio": [{"filename": "music.mp3"}]},
"bad": None,
}
}
assert [r["media_kind"] for r in client.extract_outputs(history)] == ["file", "audio"]
assert len(client.extract_outputs(history, {"music": "audio"})) == 1
assert client.extract_outputs(history, {}) == []
finally:
await client.close()
def test_reference_binding_never_promotes_same_name_or_changed_pair():
for path, record in load_companions(MANIFEST).items():
if record["binding"]["id"] not in ("02", "03", "04", "07"):
continue
api = json.loads(record["raw"])
ref = companion_protocol_reference(record["binding"], api)
assert ref["authority"] == "reference_only_not_object_info"
assert ref["target_version_match"] == "unknown"
assert ref["target_history_observed"] is False
for field in ("source_path", "source_sha256", "export_sha256"):
binding = {**record["binding"], field: "different"}
assert companion_protocol_reference(binding, api) is None
altered = copy.deepcopy(api)
altered[ref["binding"]["nodes"][0]["node_id"]]["class_type"] = "AnotherNode"
assert companion_protocol_reference(record["binding"], altered) is None
altered[ref["binding"]["nodes"][0]["node_id"]] = None
assert companion_protocol_reference(record["binding"], altered) is None
assert companion_protocol_reference(record["binding"], []) is None
raw = (REPO / path).read_bytes()
_, audit, issues = resolve_companion(record, path, raw, json.loads(raw))
assert audit["output_protocol_reference"] == ref
assert issues[0]["code"] == "companion_unverified"
# New public references must not create global auto-output recognition.
if record["binding"]["id"] in ("02", "03"):
assert auto_output_map(api) == []
async def test_protocol_doc_refresh_preserves_user_rows_and_source_values(tmp_path, monkeypatch):
await migrate_db(tmp_path / "catalogue.db")
conn = get_db(tmp_path / "catalogue.db")
records = load_companions(MANIFEST)
try:
# Simulate an earlier managed import before the protocol references existed.
with monkeypatch.context() as old:
old.setattr("calliope.comfyui.library.companion_protocol_reference", lambda *a: None)
old.setattr("calliope.comfyui.companions.companion_protocol_reference", lambda *a: None)
import_library(conn, ROOT, source_commit="fixture", companions=records)
before = {r["source_repo_path"]: dict(r) for r in conn.execute("SELECT * FROM workflows")}
user_path = next(p for p, r in records.items() if r["binding"]["id"] == "04")
conn.execute(
"UPDATE workflows SET description='用户保留' WHERE source_repo_path=?", (user_path,)
)
conn.commit()
user_before = dict(
conn.execute(
"SELECT * FROM workflows WHERE source_repo_path=?", (user_path,)
).fetchone()
)
updated = import_library(conn, ROOT, source_commit="fixture", companions=records)
assert updated["counts"] == {
"updated": 3,
"conflict": 1,
"skipped": 151,
"user_excluded": 1,
}
for path, record in records.items():
if record["binding"]["id"] not in ("02", "03", "07"):
continue
row = dict(
conn.execute("SELECT * FROM workflows WHERE source_repo_path=?", (path,)).fetchone()
)
doc = json.loads(row["doc_json"])
previous = json.loads(before[path]["doc_json"])
assert doc["params"] == previous["params"]
assert doc["source_review"] == previous["source_review"]
assert row["raw_source_json"] == before[path]["raw_source_json"]
assert json.loads(row["workflow_json"]) == json.loads(record["raw"])
assert doc["api_companion"]["binding"] == record["binding"]
assert doc["api_companion"]["output_protocol_reference"]
assert any("公开固定版本参考" in s for s in doc["steps"])
assert not row["is_enabled"] and row["import_state"] == "pending_check"
assert row["doc_completed_at"] is row["exec_verified_at"] is None
assert (
dict(
conn.execute(
"SELECT * FROM workflows WHERE source_repo_path=?", (user_path,)
).fetchone()
)
== user_before
)
assert import_library(conn, ROOT, source_commit="fixture", companions=records)[
"counts"
] == {"conflict": 1, "skipped": 154, "user_excluded": 1}
finally:
conn.close()