278 lines
14 KiB
TypeScript
278 lines
14 KiB
TypeScript
import { afterEach, describe, expect, it, vi } from 'vitest'
|
|
import { flushPromises } from '@vue/test-utils'
|
|
import { effectScope, ref } from 'vue'
|
|
import { useWorkflowExecution } from '@/features/workflows/execution'
|
|
import type { WorkflowExecution } from '@/features/workflows/execution.types'
|
|
import { ApiError, optionalResource, request } from '@/lib/http'
|
|
import { projectsApi } from '@/features/projects/api'
|
|
import { breakdownApi } from '@/features/breakdown/api'
|
|
import { storyboardApi } from '@/features/storyboard/api'
|
|
import { subjectImagesApi } from '@/features/subject-images/api'
|
|
import { subjectIdentityApi } from '@/features/subject-identity/api'
|
|
import { productionApi } from '@/features/production/api'
|
|
|
|
afterEach(() => {
|
|
vi.unstubAllGlobals()
|
|
vi.useRealTimers()
|
|
})
|
|
|
|
describe('后端 API 契约', () => {
|
|
it('图库读取与单图、批量和切换主图使用各自接口,模型由后端统一配置', async () => {
|
|
const fetcher = vi.fn<typeof fetch>().mockImplementation(async () => new Response('{"data":[]}'))
|
|
vi.stubGlobal('fetch', fetcher)
|
|
await subjectImagesApi.listForms('a/b')
|
|
await subjectImagesApi.listImages('form/id')
|
|
await subjectImagesApi.generate('form/id', {
|
|
setPrimary: false,
|
|
provider: 'qwen-image',
|
|
generationOptions: { size: '2048*2048' },
|
|
prompt: '本次提示词'
|
|
})
|
|
await subjectImagesApi.generateProject('a/b', { concurrency: 2, force: false })
|
|
await subjectImagesApi.setPrimary('form/id', 'image/id')
|
|
expect(fetcher.mock.calls.map(([url, init]) => [url, init?.method])).toEqual([
|
|
['/api/projects/a%2Fb/subject-forms', 'GET'],
|
|
['/api/subject-forms/form%2Fid/images', 'GET'],
|
|
['/api/subject-forms/form%2Fid/images', 'POST'],
|
|
['/api/projects/a%2Fb/subject-images/generate', 'POST'],
|
|
['/api/subject-forms/form%2Fid/images/image%2Fid/primary', 'PUT']
|
|
])
|
|
expect(JSON.parse(fetcher.mock.calls[2]![1]!.body as string)).toEqual({
|
|
setPrimary: false,
|
|
provider: 'qwen-image',
|
|
generationOptions: { size: '2048*2048' },
|
|
prompt: '本次提示词'
|
|
})
|
|
expect(JSON.parse(fetcher.mock.calls[3]![1]!.body as string)).toEqual({
|
|
concurrency: 2,
|
|
force: false
|
|
})
|
|
expect(fetcher.mock.calls[4]![1]!.body).toBeUndefined()
|
|
})
|
|
it('新增预览、模块批处理和稳定母版接口使用正式数据库 ID', async () => {
|
|
const fetcher = vi.fn<typeof fetch>().mockImplementation(async () => new Response('{"data":{}}'))
|
|
vi.stubGlobal('fetch', fetcher)
|
|
await subjectImagesApi.preview('form/id')
|
|
await subjectImagesApi.generatePrompts('project/id', { concurrency: 2, force: false, module: 'scene' })
|
|
await subjectImagesApi.generateProject('project/id', { concurrency: 1, force: false, module: 'prop' })
|
|
await subjectIdentityApi.generateProject('project/id', { concurrency: 2, force: false, module: 'scene' })
|
|
await subjectIdentityApi.generateStableAnchors('project/id', { module: 'prop', limit: 3, concurrency: 2 })
|
|
await productionApi.previewKeyframe('shot/id', {})
|
|
expect(fetcher.mock.calls.map(([url, init]) => [url, init?.method])).toEqual([
|
|
['/api/subject-forms/form%2Fid/images/preview', 'POST'],
|
|
['/api/projects/project%2Fid/subject-forms/generation-prompts', 'POST'],
|
|
['/api/projects/project%2Fid/subject-images/generate', 'POST'],
|
|
['/api/projects/project%2Fid/subject-identities/generate', 'POST'],
|
|
['/api/projects/project%2Fid/subject-identities/anchors/generate', 'POST'],
|
|
['/api/storyboard-shots/shot%2Fid/keyframe/preview', 'POST']
|
|
])
|
|
expect(JSON.parse(fetcher.mock.calls[4]![1]!.body as string)).toEqual({
|
|
module: 'prop',
|
|
limit: 3,
|
|
concurrency: 2
|
|
})
|
|
})
|
|
it('分镜只调用正式项目接口,并保持 force 和零次修复参数', async () => {
|
|
const fetcher = vi.fn<typeof fetch>().mockImplementation(async () => new Response('{"data":{}}'))
|
|
vi.stubGlobal('fetch', fetcher)
|
|
await storyboardApi.regenerateEpisodeShots('a/b', 3)
|
|
await storyboardApi.generateDirections('a/b', { concurrency: 2, force: false })
|
|
await storyboardApi.generateVisualStates('p', { concurrency: 3, force: true, maxRepairAttempts: 0 })
|
|
expect(fetcher.mock.calls.map(([url, init]) => [url, init?.method, JSON.parse(init!.body as string)])).toEqual([
|
|
['/api/projects/a%2Fb/storyboard-shots/regenerate', 'POST', { episodeNo: 3 }],
|
|
['/api/projects/a%2Fb/storyboard-directions/generate', 'POST', { concurrency: 2, force: false }],
|
|
[
|
|
'/api/projects/p/storyboard-visual-states/generate',
|
|
'POST',
|
|
{ concurrency: 3, force: true, maxRepairAttempts: 0 }
|
|
]
|
|
])
|
|
})
|
|
|
|
it('查询按剧集,镜头工具使用数据库 ID,读取提示词仍需显式 POST', async () => {
|
|
const fetcher = vi.fn<typeof fetch>().mockImplementation(async () => new Response('{"data":{}}'))
|
|
vi.stubGlobal('fetch', fetcher)
|
|
await storyboardApi.directions('p', 4)
|
|
await storyboardApi.visualStates('p', 4)
|
|
await storyboardApi.references('shot/id')
|
|
await storyboardApi.generationSpec('shot/id')
|
|
await storyboardApi.generatePrompt('shot/id', false)
|
|
await storyboardApi.generatePrompts('p', { concurrency: 2, force: false })
|
|
expect(fetcher.mock.calls.map(([url]) => url)).toEqual([
|
|
'/api/projects/p/storyboard-directions?episodeNo=4',
|
|
'/api/projects/p/storyboard-visual-states?episodeNo=4',
|
|
'/api/storyboard-shots/shot%2Fid/references',
|
|
'/api/storyboard-shots/shot%2Fid/generation-spec',
|
|
'/api/storyboard-shots/shot%2Fid/video-prompt',
|
|
'/api/projects/p/video-prompts/generate'
|
|
])
|
|
expect(JSON.parse(fetcher.mock.calls[4]![1]!.body as string)).toEqual({ force: false })
|
|
})
|
|
|
|
it('分镜正式批量生成保留部分失败回执,长请求不自动超时或重试', async () => {
|
|
vi.useFakeTimers()
|
|
let finish!: (response: Response) => void
|
|
const fetcher = vi.fn<typeof fetch>().mockImplementation(
|
|
() =>
|
|
new Promise(resolve => {
|
|
finish = resolve
|
|
})
|
|
)
|
|
vi.stubGlobal('fetch', fetcher)
|
|
const pending = storyboardApi.generateVisualStates('p', {
|
|
concurrency: 1,
|
|
force: false,
|
|
maxRepairAttempts: 2
|
|
})
|
|
await vi.advanceTimersByTimeAsync(120_000)
|
|
expect(fetcher).toHaveBeenCalledOnce()
|
|
expect(fetcher.mock.calls[0]?.[1]?.signal?.aborted).toBe(false)
|
|
finish(new Response('{"data":{"failedEpisodes":1,"episodes":[{"episodeNo":1,"status":"failed"}]}}'))
|
|
await expect(pending).resolves.toMatchObject({ failedEpisodes: 1, episodes: [{ status: 'failed' }] })
|
|
})
|
|
it('解包 data,同时保留创建项目的顶层 202 结构', async () => {
|
|
const fetcher = vi
|
|
.fn<(url: string, options: RequestInit) => Promise<Response>>()
|
|
.mockResolvedValueOnce(new Response(JSON.stringify({ data: [{ id: 'p1' }] })))
|
|
.mockResolvedValueOnce(
|
|
new Response(JSON.stringify({ projectId: 'p2', status: 'generating' }), { status: 202 })
|
|
)
|
|
vi.stubGlobal('fetch', fetcher)
|
|
expect(await projectsApi.list()).toEqual([{ id: 'p1' }])
|
|
expect(await projectsApi.create({ title: '测试项目', topic: '故事', style: '悬疑', episodeCount: 3 })).toEqual({
|
|
projectId: 'p2',
|
|
status: 'generating'
|
|
})
|
|
expect(JSON.parse(fetcher.mock.calls[1]![1].body as string)).toEqual({
|
|
title: '测试项目',
|
|
topic: '故事',
|
|
style: '悬疑',
|
|
episodeCount: 3
|
|
})
|
|
})
|
|
|
|
it('只将缺少 checkpoint 的 404 视为可选结果,保留服务器错误', async () => {
|
|
expect(await optionalResource(Promise.reject(new ApiError('没有 checkpoint', 404)))).toBeNull()
|
|
await expect(optionalResource(Promise.reject(new ApiError('数据库异常', 500)))).rejects.toMatchObject({
|
|
status: 500
|
|
})
|
|
})
|
|
|
|
it('保留错误细节且拒绝 HTML 代理错误', async () => {
|
|
vi.stubGlobal(
|
|
'fetch',
|
|
vi
|
|
.fn<(url: string, options: RequestInit) => Promise<Response>>()
|
|
.mockResolvedValueOnce(
|
|
new Response(JSON.stringify({ message: '校验失败', issues: ['缺少形态'] }), { status: 400 })
|
|
)
|
|
.mockResolvedValueOnce(new Response('<html>Bad Gateway</html>', { status: 502 }))
|
|
)
|
|
await expect(request('/projects')).rejects.toMatchObject({ status: 400, details: ['缺少形态'] })
|
|
await expect(request('/projects')).rejects.toThrow('服务暂时无法返回有效结果')
|
|
})
|
|
|
|
it('预览模块使用逗号参数,三种恢复不误发到 start', async () => {
|
|
const fetcher = vi
|
|
.fn<(url: string, options: RequestInit) => Promise<Response>>()
|
|
.mockImplementation(() => Promise.resolve(new Response('{"data":{}}')))
|
|
vi.stubGlobal('fetch', fetcher)
|
|
await breakdownApi.preview('a/b', { groupSize: 3, modules: ['character', 'scene'] })
|
|
for (const action of ['retry', 'resume-shots', 'resume-storyboard'] as const)
|
|
await breakdownApi.run('p', action)
|
|
expect(fetcher.mock.calls.map(call => call[0])).toEqual([
|
|
'/api/projects/a%2Fb/breakdown-preview?groupSize=3&modules=character%2Cscene',
|
|
'/api/projects/p/breakdown/retry',
|
|
'/api/projects/p/breakdown/resume-shots',
|
|
'/api/projects/p/breakdown/resume-storyboard'
|
|
])
|
|
})
|
|
|
|
it('拆解返回 202 观察句柄,后续轮询失败终态不会自动重发 POST', async () => {
|
|
vi.useFakeTimers()
|
|
/** 真实执行查询字段,开始回执与失败终态分别由不同接口返回。 */
|
|
const record: WorkflowExecution = {
|
|
id: 'http-breakdown-execution',
|
|
projectId: 'http-breakdown-project',
|
|
workflowName: 'breakdown',
|
|
status: 'running',
|
|
stage: 'breakdown',
|
|
current: 0,
|
|
total: 1,
|
|
currentResourceId: null,
|
|
metadata: null,
|
|
result: null,
|
|
error: null,
|
|
startedAt: '2026-10-08T00:00:00Z',
|
|
completedAt: null,
|
|
createdAt: '2026-10-08T00:00:00Z',
|
|
updatedAt: '2026-10-08T00:00:00Z'
|
|
}
|
|
const fetcher = vi.fn<typeof fetch>().mockImplementation(
|
|
async (_url, init) =>
|
|
new Response(
|
|
JSON.stringify({
|
|
data: init?.method === 'POST' ? { executionId: record.id, status: 'pending', total: 1 } : record
|
|
}),
|
|
{ status: init?.method === 'POST' ? 202 : 200 }
|
|
)
|
|
)
|
|
vi.stubGlobal('fetch', fetcher)
|
|
const started = await breakdownApi.run(record.projectId, 'start', { groupSize: 3, modules: ['prop'] })
|
|
expect(started).toEqual({ executionId: record.id, status: 'pending', total: 1 })
|
|
expect(fetcher.mock.calls[0]?.[0]).toBe('/api/projects/http-breakdown-project/breakdown/start')
|
|
expect(JSON.parse(String(fetcher.mock.calls[0]?.[1]?.body))).toEqual({ groupSize: 3, modules: ['prop'] })
|
|
const scope = effectScope()
|
|
const tracker = scope.run(() => useWorkflowExecution(ref(record.projectId), 'breakdown'))!
|
|
try {
|
|
await tracker.track(started.executionId)
|
|
await flushPromises()
|
|
expect(tracker.active.value).toBe(true)
|
|
expect(tracker.query.data.value?.status).toBe('running')
|
|
record.status = 'failed'
|
|
record.error = '后端抽取失败'
|
|
record.completedAt = '2026-10-08T00:01:00Z'
|
|
await vi.advanceTimersByTimeAsync(1_500)
|
|
await flushPromises()
|
|
expect(tracker.query.data.value).toMatchObject({ status: 'failed', error: '后端抽取失败' })
|
|
expect(tracker.active.value).toBe(false)
|
|
const completedCount = fetcher.mock.calls.length
|
|
await vi.advanceTimersByTimeAsync(120_000)
|
|
expect(fetcher).toHaveBeenCalledTimes(completedCount)
|
|
expect(fetcher.mock.calls.filter(([, init]) => init?.method === 'POST')).toHaveLength(1)
|
|
expect(
|
|
fetcher.mock.calls
|
|
.slice(1)
|
|
.every(
|
|
([url, init]) =>
|
|
url === '/api/workflow-executions/http-breakdown-execution' && init?.method === 'GET'
|
|
)
|
|
).toBe(true)
|
|
} finally {
|
|
tracker.dismiss()
|
|
scope.stop()
|
|
}
|
|
})
|
|
})
|
|
|
|
/** 同步版本冲突保留顶层错误码,资源与版本 ID 只位于 details。 */
|
|
it('保留版本冲突的顶层 code 与独立 details', async () => {
|
|
const details = { shotId: 's1', currentActiveRevisionId: 'r2' }
|
|
vi.stubGlobal(
|
|
'fetch',
|
|
vi
|
|
.fn<typeof fetch>()
|
|
.mockResolvedValue(
|
|
new Response(
|
|
JSON.stringify({ code: 'MOTION_PLAN_REVISION_CONFLICT', message: '生效版本变化', details }),
|
|
{ status: 409 }
|
|
)
|
|
)
|
|
)
|
|
await expect(request('/test')).rejects.toMatchObject({
|
|
status: 409,
|
|
code: 'MOTION_PLAN_REVISION_CONFLICT',
|
|
details
|
|
})
|
|
})
|