astrbot_plugin_imagestudio/tests/test_workflow_rounds.py

358 行
12 KiB
Python

from __future__ import annotations
import json
from pathlib import Path
import pytest
from backend.dto.common import ApiError
from backend.dto.job_dto import GenerationTask
from backend.dto.workflow_dto import WorkflowNode
from backend.services.workflow_round_service import WorkflowRoundService
from core.audit_service import AuditService
from core.identity import RequestContext
from database.db_helper import Database, DatabaseSettings, SqliteSettings
from database.models import table_spec
from database.repositories.image_repository import ImageRepository
from database.repositories.job_repository import JobRepository
from database.repositories.workflow_repository import WorkflowRepository
from database.repositories.workflow_round_repository import WorkflowRoundRepository
from engines.single_flow import SingleFlowEngine
def _database(tmp_path: Path) -> Database:
database = Database(
DatabaseSettings(
backend="sqlite",
sqlite=SqliteSettings(path=str(tmp_path / "workflow-rounds.sqlite3")),
)
)
database.initialize()
return database
def _fixture(database: Database) -> None:
conn = database.connect()
try:
conn.execute(
"""
INSERT INTO character_profiles (
profile_id, name, owner_platform, owner_user_id, status, metadata_json
) VALUES (?, ?, ?, ?, ?, ?)
""",
("profile-round", "Round test", "webui", "system", "active", "{}"),
)
conn.execute(
"""
INSERT INTO profile_workflows (
workflow_id, profile_id, workflow_type, display_name, status,
current_node_id, current_branch, metadata_json
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
""",
(
"workflow-round",
"profile-round",
"character_gradual",
"Round workflow",
"running",
"node-headshot",
"main",
json.dumps(
{
"character_execution": {
"executor": "character_workflow",
"import_confirmed": True,
"progression_version": "character_gradual_sequential_v1",
}
}
),
),
)
conn.execute(
"""
INSERT INTO workflow_nodes (
node_id, workflow_id, node_key, title, node_type, status,
branch_name, prompt, negative_prompt, model_route, sort_order, metadata_json
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
"node-headshot",
"workflow-round",
"headshot",
"头像",
"generation",
"draft",
"main",
"one stable character portrait",
"identity drift",
"portrait-route",
40,
"{}",
),
)
conn.commit()
finally:
conn.close()
def _service(database: Database) -> WorkflowRoundService:
return WorkflowRoundService(
round_repository=WorkflowRoundRepository(database),
workflow_repository=WorkflowRepository(database),
image_repository=ImageRepository(database),
job_repository=JobRepository(database),
audit_service=AuditService(database),
)
def test_round_migration_is_idempotent_and_declared_in_table_metadata(tmp_path: Path) -> None:
database = _database(tmp_path)
database.initialize()
conn = database.connect()
try:
tables = {
str(row["name"])
for row in conn.execute("SELECT name FROM sqlite_master WHERE type = 'table'").fetchall()
}
indexes = {
str(row["name"])
for row in conn.execute("SELECT name FROM sqlite_master WHERE type = 'index'").fetchall()
}
finally:
conn.close()
assert {
"workflow_generation_rounds",
"workflow_generation_candidates",
"workflow_round_candidate_pool",
} <= tables
assert {
"idx_workflow_rounds_sequence",
"idx_workflow_candidates_origin_index",
"idx_round_candidate_pool_final",
} <= indexes
assert table_spec("generation_images") is not None
assert table_spec("workflow_history") is not None
assert table_spec("workflow_branches") is not None
assert table_spec("workflow_generation_rounds") is not None
assert table_spec("workflow_generation_candidates") is not None
assert table_spec("workflow_round_candidate_pool") is not None
def test_round_migration_stays_sqlite_and_postgresql_portable() -> None:
migration = Path("database/migrations/0014_workflow_generation_rounds.sql").read_text(encoding="utf-8")
upper = migration.upper()
assert "AUTOINCREMENT" not in upper
assert "PRAGMA" not in upper
assert "WITHOUT ROWID" not in upper
assert "CREATE TABLE IF NOT EXISTS" in upper
assert "WHERE IS_FINAL = 1" in upper
def test_create_round_reserves_stable_codes_and_replays_idempotently(tmp_path: Path) -> None:
database = _database(tmp_path)
_fixture(database)
service = _service(database)
ctx = RequestContext.system("workflow-round-test")
created = service.create_round(
"node-headshot",
{
"count": 4,
"idempotency_key": "round-request-1",
"reference_snapshot": {"material_ids": ["material-a"]},
},
ctx,
)
assert created["created"] is True
assert created["round"]["display_code"] == "TX-01"
assert created["round"]["requested_count"] == 4
assert created["round"]["status"] == "draft"
assert [item["display_code"] for item in created["candidates"]] == [
"TX-01-01",
"TX-01-02",
"TX-01-03",
"TX-01-04",
]
assert all(item["candidate"]["generation_status"] == "planned" for item in created["candidates"])
assert all(item["image"] is None and item["task"] is None for item in created["candidates"])
replayed = service.create_round(
"node-headshot",
{"count": 5, "idempotency_key": "round-request-1"},
ctx,
)
assert replayed["created"] is False
assert replayed["idempotent_replay"] is True
assert replayed["round"]["round_id"] == created["round"]["round_id"]
assert len(replayed["candidates"]) == 4
second = service.create_round(
"node-headshot",
{"count": 1, "idempotency_key": "round-request-2"},
ctx,
)
assert second["round"]["display_code"] == "TX-02"
conn = database.connect()
try:
history_count = conn.execute(
"SELECT COUNT(*) AS total FROM workflow_history WHERE action = 'round_created'"
).fetchone()["total"]
finally:
conn.close()
assert int(history_count) == 2
def test_legacy_images_are_exposed_as_a_read_only_synthetic_round(tmp_path: Path) -> None:
database = _database(tmp_path)
_fixture(database)
images = ImageRepository(database)
images.create(
{
"image_id": "image-legacy-a",
"profile_id": "profile-round",
"workflow_id": "workflow-round",
"node_id": "node-headshot",
"image_uri": "storage://images/legacy/a.png",
"positive_prompt": "portrait a",
"model_route": "portrait-route",
"metadata": {"provider_id": "provider-a", "provider_model": "model-a"},
}
)
images.create(
{
"image_id": "image-legacy-b",
"profile_id": "profile-round",
"workflow_id": "workflow-round",
"node_id": "node-headshot",
"image_uri": "storage://images/legacy/b.png",
"positive_prompt": "portrait b",
"model_route": "portrait-route",
"is_selected": True,
"metadata": {"provider_id": "provider-a", "provider_model": "model-a"},
}
)
service = _service(database)
result = service.list_node_rounds("node-headshot")
assert result["legacy_adapter_used"] is True
assert result["total"] == 1
detail = result["items"][0]
assert detail["legacy"] is True
assert detail["read_only"] is True
assert detail["round"]["round_id"] == "legacy-round-node-headshot"
assert detail["round"]["display_code"] == "TX-L01"
assert [item["display_code"] for item in detail["candidates"]] == ["TX-L01-01", "TX-L01-02"]
assert detail["candidates"][1]["is_final"] is True
assert detail["candidates"][1]["candidate"]["provider_model"] == "model-a"
assert service.get_round("legacy-round-node-headshot").legacy is True
conn = database.connect()
try:
persisted = conn.execute("SELECT COUNT(*) AS total FROM workflow_generation_rounds").fetchone()["total"]
finally:
conn.close()
assert int(persisted) == 0
class _TempStorage:
def __init__(self, root: Path):
self.root = root
def resolve_uri(self, uri: str) -> Path:
assert uri.startswith("storage://")
storage_root, relative = uri[len("storage://") :].split("/", 1)
return self.root / storage_root / relative
def _node() -> WorkflowNode:
return WorkflowNode(
node_id="node-headshot",
workflow_id="workflow-round",
node_key="headshot",
title="头像",
description=None,
step_name="headshot",
node_type="generation",
status="running",
branch_name="main",
prompt="portrait",
negative_prompt=None,
model_route="portrait-route",
selected_image_id=None,
sort_order=40,
metadata={},
created_at="2026-07-15T00:00:00+00:00",
updated_at="2026-07-15T00:00:00+00:00",
)
def _task() -> GenerationTask:
return GenerationTask(
task_id="task-scoped",
profile_id="profile-round",
workflow_id="workflow-round",
node_id="node-headshot",
task_type="generation",
status="running",
model_route="portrait-route",
progress=20,
idempotency_key=None,
request={},
result={},
error_message=None,
metadata={},
created_at="2026-07-15T00:00:00+00:00",
updated_at="2026-07-15T00:00:00+00:00",
)
def test_single_flow_uses_scoped_round_paths_without_breaking_legacy_paths(tmp_path: Path) -> None:
engine = SingleFlowEngine(storage=_TempStorage(tmp_path), allow_mock_fallback=True)
scoped = engine.generate(
_node(),
_task(),
{
"count": 1,
"output_scope": {
"workflow_id": "workflow-round",
"branch_name": "main",
"node_key": "headshot",
"round_id": "round-1",
"round_display_code": "TX-01",
"candidate_id": "candidate-1",
"candidate_display_code": "TX-01-01",
},
},
)
assert scoped[0].image_uri.startswith(
"storage://images/workflows/workflow-round/main/headshot/TX-01__round-1/"
)
assert "TX-01-01__candidate-1__task-scoped_01.png" in scoped[0].image_uri
assert scoped[0].metadata["scoped_output"] is True
assert _TempStorage(tmp_path).resolve_uri(scoped[0].image_uri).is_file()
legacy = engine.generate(_node(), _task(), {"count": 1})
assert legacy[0].image_uri == "storage://images/single/task-scoped_1.png"
def test_confirmed_node_cannot_receive_a_new_round_without_a_branch(tmp_path: Path) -> None:
database = _database(tmp_path)
_fixture(database)
conn = database.connect()
try:
conn.execute(
"UPDATE workflow_nodes SET status = 'selected', selected_image_id = 'image-confirmed' WHERE node_id = ?",
("node-headshot",),
)
conn.commit()
finally:
conn.close()
with pytest.raises(ApiError) as error:
_service(database).create_round("node-headshot", {"count": 4}, RequestContext.system("test"))
assert error.value.details["required_action"] == "create_branch"