astrbot_plugin_imagestudio/tests/test_frontend_api_contract.py

492 行
25 KiB
Python

2026-07-05 21:17:39 +08:00
from __future__ import annotations
import re
import unittest
from pathlib import Path
from backend.route_registry import route_manifest
from database.db_helper import REPO_ROOT
class FrontendApiContractTests(unittest.TestCase):
def test_static_frontend_endpoints_exist_in_backend_registry(self):
2026-07-05 22:59:44 +08:00
endpoint_source = _endpoint_source()
2026-07-05 21:17:39 +08:00
frontend_static = {
match.group("endpoint")
for match in re.finditer(r"\w+:\s*\"(?P<endpoint>[^\"]+)\"", endpoint_source)
if "${" not in match.group("endpoint")
}
backend_endpoints = {route["endpoint"] for route in route_manifest()}
self.assertTrue(frontend_static)
self.assertEqual(sorted(frontend_static - backend_endpoints), [])
2026-07-05 22:59:44 +08:00
def test_dynamic_frontend_endpoints_exist_in_backend_registry(self):
endpoint_source = _endpoint_source()
frontend_dynamic = {
_expand_frontend_template(match.group("template"))
for match in re.finditer(
r"\w+:\s*\((?P<params>[^)]*)\)\s*=>\s*`(?P<template>[^`]+)`",
endpoint_source,
)
}
backend_expanded = {_expand_backend_endpoint(route["endpoint"]) for route in route_manifest()}
self.assertTrue(frontend_dynamic)
self.assertEqual(sorted(frontend_dynamic - backend_expanded), [])
def test_api_client_supports_nested_astrbot_envelopes_and_method_override(self):
source = _frontend_source("shared", "api", "client.ts")
self.assertIn('current.status === "error"', source)
self.assertIn("current = current.data", source)
self.assertIn('const METHOD_OVERRIDE_KEY = "__imagestudio_method"', source)
self.assertIn('const METHOD_OVERRIDE_BODY_KEY = "__imagestudio_body"', source)
self.assertIn('["PUT", "PATCH", "DELETE"].includes(method)', source)
self.assertIn('method === "DELETE" ? {}', source)
self.assertIn('throw new ApiClientError("bridge_method_unavailable"', source)
def test_plugin_page_hosts_the_full_workbench_and_html_shells_are_complete(self):
plugin_app = _frontend_source("plugin-page", "src", "App.vue")
self.assertIn('import WorkbenchApp from "../../standalone-web/src/App.vue"', plugin_app)
self.assertIn("<WorkbenchApp />", plugin_app)
self.assertNotIn("/web", plugin_app)
for project in ("plugin-page", "standalone-web"):
html = _frontend_source(project, "index.html").lower()
self.assertIn("<!doctype html>", html)
self.assertIn('<meta charset="utf-8"', html)
self.assertIn('name="viewport"', html)
def test_workbench_is_split_into_reusable_components_and_feature_modules(self):
source = _frontend_source("standalone-web", "src", "App.vue")
navigation = _frontend_source("standalone-web", "src", "components", "AppNavigationRail.vue")
viewer = _frontend_source("standalone-web", "src", "components", "ImagePreviewDialog.vue")
profile_import = _frontend_source(
"standalone-web", "src", "features", "quick-profile", "profile-import.ts"
)
for component in (
"AppNavigationRail",
"ImagePreviewDialog",
"MaterialCategoryCreateDialog",
"MaterialDetailDialog",
"MaterialOperationDialog",
"MetricCardGrid",
"StateCard",
"EmptyState",
):
self.assertIn(f"<{component}", source)
self.assertIn('aria-current="props.activeKey === item.key ? \'page\' : undefined"', navigation)
self.assertIn('@click.self="close"', viewer)
self.assertIn("export function parseExternalProfileImport", profile_import)
self.assertNotIn("function parseExternalProfileImport", source)
def test_profiles_navigation_renders_the_dedicated_feature_page(self):
source = _frontend_source("standalone-web", "src", "App.vue")
navigation = _frontend_source(
"standalone-web", "src", "features", "navigation", "navigation-config.ts"
)
profiles_branch = _source_between(
source,
'<template v-else-if="activeNav === \'profiles\'">',
'<template v-else-if="activeNav === \'materials\'">',
)
profiles_nav_item = _source_between(
navigation,
'key: "profiles"',
'key: "materials"',
)
self.assertIn('import ProfilesPage from "./features/profiles/ProfilesPage.vue"', source)
self.assertIn("<ProfilesPage", profiles_branch)
self.assertIn('data-module="profiles"', profiles_branch)
self.assertIn('module: "profiles"', profiles_nav_item)
def test_profiles_page_exposes_states_and_primary_actions(self):
page = _frontend_source(
"standalone-web", "src", "features", "profiles", "ProfilesPage.vue"
)
master = _frontend_source(
"standalone-web", "src", "features", "profiles", "ProfileMasterPane.vue"
)
self.assertIn('v-if="loading && !profiles.length"', master)
self.assertIn('v-if="error"', page)
self.assertNotIn('v-else-if="!backendConnected"', page)
self.assertIn('v-if="showBackendConnectionBanner"', _frontend_source("standalone-web", "src", "App.vue"))
self.assertIn('v-else-if="!filteredProfiles.length"', master)
self.assertIn('v-else class="detail-empty"', page)
self.assertIn(':loading="loading"', page)
for event in ("create", "import", "generate", "workflow", "materials"):
self.assertIn(f" {event}: []", page)
self.assertIn(f"emit('{event}')", page)
def test_profiles_list_avoids_workflow_n_plus_one_and_details_load_on_selection(self):
source = _frontend_source("standalone-web", "src", "App.vue")
profile_items = _source_between(
source,
"const previewCharacterProfiles",
"const selectedProfilePage =",
)
profile_loader = _source_between(
source,
"async function loadBackendQuickProfiles",
"async function loadProfilePageDetails",
)
profile_details_loader = _source_between(
source,
"async function loadProfilePageDetails",
"async function resolveProfileAvatar",
)
self.assertIn('source: "sample"', profile_items)
self.assertIn('backendConnection.value.state === "connected"', profile_items)
self.assertIn("? backendProfiles.value : previewCharacterProfiles.value", profile_items)
self.assertIn("getJson<ProfileListResult>(endpoints.profiles", profile_loader)
self.assertIn("loadRemainingProfilePages(firstPage)", profile_loader)
self.assertIn("pageCount - 1", profile_loader)
self.assertNotIn("endpoints.profileWorkflows", profile_loader)
self.assertIn(
"getJson<ProfileWorkflow[]>(endpoints.profileWorkflows(profile.profile_id))",
profile_details_loader,
)
def test_profile_generation_categories_and_text_profile_actions_are_wired(self):
source = _frontend_source("standalone-web", "src", "App.vue")
master = _frontend_source(
"standalone-web", "src", "features", "profiles", "ProfileMasterPane.vue"
)
detail = _frontend_source(
"standalone-web", "src", "features", "profiles", "ProfileDetailPane.vue"
)
profile_ui = _frontend_source(
"standalone-web", "src", "features", "profiles", "profile-ui.ts"
)
generation_actions = _source_between(
source,
"async function startSelectedProfileGeneration",
"function openSelectedProfileWorkspace",
)
questionnaire_save = _source_between(
source,
"async function generateQuickProfileArchiveFromQuestionnaire",
"function buildQuickProfileDraftPayload",
)
continue_action = _source_between(
source,
"async function continueSelectedProfileWorkflow",
"function openSelectedProfileWorkspace",
)
workflow_resource = _source_between(
detail,
"<span>生成工作流</span>",
"</section>\n </div>",
)
for label in ("未生成", "快速角色", "详细角色"):
self.assertIn(label, master)
self.assertIn(label, profile_ui)
self.assertIn('role="group" aria-label="角色分类"', master)
self.assertIn("repeat(4, minmax(0, 1fr))", master)
self.assertIn('emit("select", "")', master)
self.assertIn("profileGenerationKind(profile)", master)
self.assertIn("generationKind === 'ungenerated'", detail)
self.assertIn("生成快速角色", detail)
self.assertIn("创建详细工作流", detail)
self.assertIn('role="group" aria-label="角色详情视图"', detail)
self.assertLess(
detail.index('class="generation-error"'),
detail.index('<div v-if="activeTab === \'overview\'"'),
)
self.assertNotIn("<button", workflow_resource)
self.assertIn('mode === "quick" ? QUICK_CHARACTER_WORKFLOW_TYPE : CHARACTER_WORKFLOW_TYPE', generation_actions)
self.assertIn("ensureCharacterWorkflowForProfile(editorProfile, workflowType)", generation_actions)
self.assertIn("endpoints.workflowExecuteCharacter(workflow.workflow_id)", generation_actions)
self.assertIn('if (profileGenerationKind(profile) === "ungenerated") return []', source)
self.assertIn('if (profile.metadata?.source !== "sample")', source)
self.assertIn("profileGenerationBusyByProfileId", generation_actions)
self.assertIn("nextCharacterWorkflowId(profile.profileId, workflowType, workflows)", source)
self.assertIn('["running", "completed"].includes(normalizeStatus(workflow.status))', generation_actions)
self.assertIn("openProfileWorkspace(profile.profile_id, \"workflow\")", generation_actions)
self.assertIn("invalidateProfileDetailsRequests(profile.profile_id)", generation_actions)
self.assertNotIn("ensureCharacterWorkflowForProfile(profile)", questionnaire_save)
self.assertIn('activeGenerateMode.value = "quickProfile"', questionnaire_save)
self.assertIn('if (source === "quick_profile") return "快速问卷建档"', profile_ui)
self.assertIn("PROFILE_NO_SELECTION_ID", source)
self.assertIn("getJson<ProfileWorkflow[]>(endpoints.profileWorkflows(profile.profile_id))", continue_action)
self.assertIn("needsCreation", continue_action)
self.assertNotIn("backendWriteBlockMessage", continue_action)
def test_profile_wardrobe_uses_real_endpoints_categories_and_confirmed_materials(self):
source = _frontend_source("standalone-web", "src", "App.vue")
detail = _frontend_source(
"standalone-web", "src", "features", "profiles", "ProfileDetailPane.vue"
)
wardrobe = _frontend_source(
"standalone-web", "src", "features", "profiles", "ProfileWardrobePane.vue"
)
wardrobe_loader = _source_between(
source,
"async function loadProfileWardrobe",
"async function hydrateWardrobeMaterials",
)
wardrobe_actions = _source_between(
source,
"function profileWardrobeWriteBlockMessage",
"function openSelectedProfileWorkspace",
)
self.assertIn("ProfileWardrobePane", detail)
self.assertIn("activeTab === 'wardrobe'", detail)
self.assertIn("getJson<WardrobeItem[]>(endpoints.wardrobe(profileId))", wardrobe_loader)
self.assertIn("postJson<WardrobeItem>(endpoints.wardrobeItems(profile.profile_id)", wardrobe_actions)
self.assertIn("material_id: materialId", wardrobe_actions)
self.assertIn("wardrobe_category: category", wardrobe_actions)
self.assertIn("deleteJson<WardrobeItem>(endpoints.wardrobeItem(profile.profile_id, wardrobeItemId))", wardrobe_actions)
self.assertIn('profile.metadata?.source === "sample"', wardrobe_loader)
self.assertIn("bootstrap.value?.feature_flags.wardrobe", wardrobe_loader)
self.assertIn('material.recognition_status.trim().toLowerCase() === "confirmed"', wardrobe)
self.assertIn("!wardrobeMaterialIds.value.has(material.material_id)", wardrobe)
self.assertIn('["top", "bottom", "dress", "shoes", "accessory"]', wardrobe)
self.assertIn("props.permissions?.can_manage_materials", wardrobe)
self.assertNotIn("props.permissions?.can_write &&", wardrobe)
self.assertIn("nextProfileWardrobeRequestGeneration(profileId)", wardrobe_loader)
self.assertIn("isCurrentProfileWardrobeRequest(profileId, requestGeneration)", wardrobe_loader)
self.assertIn("profileWardrobeLoadingByProfileId", source)
self.assertIn("loadRemainingMaterialPages(firstMaterialPage)", source)
self.assertIn("pageCount - 1", source)
self.assertGreaterEqual(
wardrobe_actions.count("invalidateProfileWardrobeRequests(profile.profile_id)"),
4,
)
def test_ui_does_not_present_demo_data_as_connected_backend_data(self):
source = _frontend_source("standalone-web", "src", "App.vue")
model_options = _source_between(source, "const imageModelOptions", "const selectedImageModelOption")
material_cards = _source_between(source, "const rawMaterialLibraryCards", "const activeMaterialCategoryId")
self.assertIn('backendConnection.value.state === "preview"', model_options)
self.assertIn(": []", model_options)
self.assertIn('["preview", "error"].includes(backendConnection.value.state)', material_cards)
self.assertIn("return []", material_cards)
self.assertIn("请先在设置中配置并确认一个生图模型", source)
self.assertIn("尚未配置生图模型", source)
self.assertNotIn("使用本地模型", source)
def test_workbench_keyboard_navigation_and_real_overview_actions_are_wired(self):
source = _frontend_source("standalone-web", "src", "App.vue")
self.assertIn('role="combobox"', source)
self.assertIn('role="listbox"', source)
self.assertIn("moveSearchSelection(1)", source)
self.assertIn('event.key.toLowerCase() === "k"', source)
self.assertIn('aria-current="props.activeKey === item.key ? \'page\' : undefined"', _frontend_source(
"standalone-web", "src", "components", "AppNavigationRail.vue"
))
self.assertIn('@click="openQueueJob(job)"', source)
self.assertIn('@click="retryQueueJob(job)"', source)
self.assertIn("function canRetryQueueJob", source)
self.assertIn("@click=\"setActiveNav('settings', 'settings')\"", source)
self.assertIn("@click=\"setActiveNav('materials', 'images')\"", source)
def test_workflow_details_and_generated_images_use_safe_frontend_contracts(self):
source = _frontend_source("standalone-web", "src", "App.vue")
self.assertIn("getJson<WorkflowDetail>(endpoints.workflow(", source)
self.assertNotIn("getJson<ProfileWorkflow>(endpoints.workflow(", source)
self.assertIn("function isAuthenticGenerationImage", source)
self.assertIn("metadata.mock", source)
self.assertIn('"provider_error"', source)
self.assertIn("images.filter(isAuthenticGenerationImage)", source)
self.assertIn("selectedWorkflowDraftImages.value\n .filter(isAuthenticGenerationImage)", source)
def test_quick_profile_never_submits_sample_material_ids_or_creates_on_selection(self):
source = _frontend_source("standalone-web", "src", "App.vue")
self.assertIn('normalized.startsWith("qp-material-")', source)
self.assertNotIn("material_id: profile.materialId", source)
for selected_ids_expression in re.findall(r"selected_material_ids:\s*([^,\n]+)", source):
self.assertNotIn(".map", selected_ids_expression)
self.assertIn("selectedQuickProfileMaterialIdsForApi", selected_ids_expression)
self.assertIn("if (profile.profileId && profile.workflowId)", source)
self.assertIn("characterWorkflowEnsureRequests", source)
def test_quick_profile_picker_uses_confirmed_backend_materials_and_reports_real_bindings(self):
source = _frontend_source("standalone-web", "src", "App.vue")
self.assertIn("const backendQuickProfileMaterialOptions = computed<QuickProfileMaterialOption[]>", source)
self.assertIn('normalizeStatus(material.recognition_status) === "confirmed"', source)
self.assertIn("function quickProfileMaterialOptionFromBackend", source)
self.assertIn("id: material.material_id", source)
self.assertIn("quickProfileSelectableMaterials.value.filter(", source)
self.assertIn("workflowNodeActionError.value = payload.selected_material_ids.length", source)
self.assertNotIn("workflowNodeActionError.value = selectedQuickProfileMaterials.value.length", source)
def test_created_workflow_link_updates_backend_profile_state(self):
source = _frontend_source("standalone-web", "src", "App.vue")
self.assertIn("function updateQuickProfileWorkflowLink", source)
self.assertIn(
"backendQuickProfileLibraryItems.value = backendQuickProfileLibraryItems.value.map(applyWorkflowLink)",
source,
)
self.assertNotIn("updateLocalQuickProfileWorkflowLink", source)
def test_job_retry_ui_describes_synchronous_execution_contract(self):
source = _frontend_source("standalone-web", "src", "App.vue")
presentation = _frontend_source("shared", "utils", "presentation.ts")
self.assertIn("立即使用原请求创建并执行新任务", source)
self.assertIn('endpoints.jobDeadLetterRetry, { limit: 5 }', source)
self.assertIn('retrying: "重试执行中"', presentation)
self.assertIn('superseded: "已被重试替代"', presentation)
self.assertIn("死信任务已重新执行", source)
self.assertIn('recordString(err.details, "replacement_task_id")', source)
self.assertIn("失败的替代任务", source)
self.assertIn('["completed", "succeeded", "superseded"]', source)
self.assertNotIn('["failed", "dead_letter", "cancelled", "superseded"]', source)
self.assertNotIn("死信任务已重新排队", source)
def test_completed_generation_nodes_can_persist_selection_without_unlocking_generation(self):
source = _frontend_source("standalone-web", "src", "App.vue")
selection_source = _source_between(
source,
"function toggleWorkflowDraftSelection",
"async function submitImageGenerationPrompt",
)
generation_source = _source_between(
source,
"async function runSelectedWorkflowNodeGeneration",
"async function enterWorkflowPersonaSplit",
)
self.assertIn("if (isSelectedWorkflowNodeLocked.value)", selection_source)
self.assertNotIn("if (isSelectedWorkflowNodeWriteLocked.value) return", selection_source)
self.assertIn("endpoints.nodeSelectImage(backendNodeId)", selection_source)
self.assertIn("selected_image_id: selected.image_id", selection_source)
self.assertIn('workflowLockedNodeWriteMessage(options.retry ? "节点重跑" : "节点生成")', generation_source)
self.assertIn(':disabled="isSelectedWorkflowNodeLocked"', source)
def test_daily_cost_uses_real_usage_and_does_not_claim_zero_without_pricing(self):
source = _frontend_source("standalone-web", "src", "App.vue")
endpoint_source = _endpoint_source()
self.assertIn('costUsage: "costs/usage"', endpoint_source)
self.assertIn("getJson<CostUsageSummary>(endpoints.costUsage, { days: 1 })", source)
self.assertIn('"未配置可信价格"', source)
self.assertIn('";不按零成本展示"', source)
self.assertNotIn('label: "今日成本",\n value: "未接入"', source)
def test_material_page_actions_use_real_forms_and_backend_endpoints(self):
source = _frontend_source("standalone-web", "src", "App.vue")
dialog = _frontend_source("standalone-web", "src", "components", "MaterialOperationDialog.vue")
upload_card = _source_between(source, 'id: "upload"', 'id: "create-category"')
asset_pack_card = _source_between(source, 'id: "asset-pack"', 'id: "wardrobe"')
wardrobe_card = _source_between(source, 'id: "wardrobe"', 'id: "workflow-bind"')
self.assertIn('title: "登记素材 URI"', source)
self.assertIn("postJson<Material>(endpoints.materialUpload", source)
self.assertIn("postJson<AssetImportPlan>(endpoints.assetImportPack", source)
self.assertIn("dry_run: true", source)
self.assertIn("dry_run: false", source)
self.assertIn("postJson<WardrobeItem>(endpoints.wardrobeImportMaterial", source)
self.assertNotIn("这个入口需要表单承接", source)
self.assertNotIn("预留入口", source)
self.assertNotIn('uploaded: "已上传"', source)
self.assertIn('uploaded: "URI 已登记"', source)
self.assertNotIn("enabled: false", upload_card)
self.assertNotIn("enabled: false", asset_pack_card)
self.assertNotIn("enabled: false", wardrobe_card)
self.assertIn("不会从浏览器上传文件字节", dialog)
self.assertIn("storage:// URI", dialog)
self.assertIn("dry-run 摘要", dialog)
self.assertIn('emit("executeAssetPack"', dialog)
self.assertIn("wardrobe_category", dialog)
self.assertIn('props.material.recognition_status !== "confirmed"', dialog)
def test_material_operation_dialog_reuses_shared_uri_helpers_and_accessible_close_behavior(self):
dialog = _frontend_source("standalone-web", "src", "components", "MaterialOperationDialog.vue")
presentation = _frontend_source("shared", "utils", "presentation.ts")
storage_uri = _frontend_source("shared", "utils", "storage-uri.ts")
self.assertIn('from "../../../shared/utils/presentation"', dialog)
self.assertIn('from "../../../shared/utils/storage-uri"', dialog)
self.assertNotIn("function formatBytes", dialog)
self.assertNotIn("function isStorageUri", dialog)
self.assertIn("export function formatBytes", presentation)
self.assertIn("export function isStorageUri", storage_uri)
self.assertIn("export function storageFilename", storage_uri)
self.assertIn("export function isSupportedImageStorageUri", storage_uri)
self.assertIn("png|jpe?g|gif|webp", storage_uri)
self.assertIn("PNG、JPG、JPEG、GIF 或 WEBP", dialog)
self.assertIn('@click.self="requestClose"', dialog)
self.assertIn(':aria-busy="busy"', dialog)
self.assertIn('event.key === "Escape"', dialog)
self.assertIn("if (props.busy) return", dialog)
self.assertIn('event.key !== "Tab"', dialog)
self.assertIn("firstInputRef.value?.focus()", dialog)
def test_capability_copy_describes_metadata_only_profiles(self):
source = _frontend_source("standalone-web", "src", "App.vue")
self.assertIn("能力档案", source)
self.assertIn("metadata-only", source)
self.assertNotIn("能力探测", source)
def test_node_retry_posts_generation_payload_once_and_reuses_generate_result_handling(self):
source = _frontend_source("standalone-web", "src", "App.vue")
retry_source = _source_between(
source,
"async function runSelectedWorkflowNodeGeneration",
"async function enterWorkflowPersonaSplit",
)
self.assertIn("const generationPayload = {", retry_source)
self.assertIn("? endpoints.nodeRetry(backendNodeId)", retry_source)
self.assertIn(": endpoints.nodeGenerate(backendNodeId)", retry_source)
self.assertEqual(retry_source.count("postJson<NodeGenerateResult>"), 1)
self.assertIn("hydrateGenerationImages(result.images ?? [])", retry_source)
self.assertNotIn("postJson<WorkflowNode>(endpoints.nodeRetry", retry_source)
2026-07-05 22:59:44 +08:00
def _endpoint_source() -> str:
return (REPO_ROOT / "frontend" / "shared" / "api" / "endpoints.ts").read_text(encoding="utf-8")
def _frontend_source(*relative_parts: str) -> str:
return (REPO_ROOT / "frontend" / Path(*relative_parts)).read_text(encoding="utf-8")
def _source_between(source: str, start: str, end: str) -> str:
return source[source.index(start) : source.index(end)]
2026-07-05 22:59:44 +08:00
def _expand_frontend_template(template: str) -> str:
return re.sub(r"\$\{(?P<param>\w+)\}", lambda match: _sample_value(match.group("param")), template)
def _expand_backend_endpoint(endpoint: str) -> str:
return re.sub(r"\{(?P<param>[^{}]+)\}", lambda match: _sample_value(match.group("param")), endpoint)
def _sample_value(param_name: str) -> str:
normalized = re.sub(r"(?<!^)([A-Z])", r"_\1", param_name).lower()
samples = {
"category_id": "category_sample",
"image_id": "image_sample",
"material_id": "material_sample",
"node_id": "node_sample",
"profile_id": "profile_sample",
"snapshot_id": "snapshot_sample",
"task_id": "task_sample",
"wardrobe_item_id": "wardrobe_item_sample",
"workflow_id": "workflow_sample",
}
return samples.get(normalized, f"{normalized}_sample")
2026-07-05 21:17:39 +08:00
if __name__ == "__main__":
unittest.main()