Files
short-drama-agent-front/tests/features/production/effective-keyframe-quality.test.ts
T

290 lines
12 KiB
TypeScript

import { effectScope, ref } from 'vue'
import { flushPromises, mount } from '@vue/test-utils'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { useKeyframeVision } from '@/features/production/keyframe-vision'
import { useEffectiveKeyframeQuality } from '@/features/production/effective-keyframe-quality'
import { qualityApi, type EffectiveKeyframeQualityStatus } from '@/features/production/quality-api'
import KeyframeCard from '@/features/production/components/KeyframeCard.vue'
import KeyframeValidationHistory from '@/features/production/components/KeyframeValidationHistory.vue'
import QualityResult from '@/features/production/components/QualityResult.vue'
import type { ShotKeyframe } from '@/features/production/types'
/** 隔离作用域和组件,每例结束关闭观察及定时器。 */
let scope = effectScope()
/** 当前测试组件的清理入口。 */
let unmount = () => {}
afterEach(() => {
unmount()
scope.stop()
scope = effectScope()
sessionStorage.clear()
})
/**
* 正式接口隔离响应。
* @param data 模拟业务数据
* @returns HTTP 响应
*/
function response(data: unknown) {
return new Response(JSON.stringify({ data }))
}
/**
* 构造带历史 Passed 的当前质量,默认不开放人工接受。
* @param status 当前有效状态
* @param manualReviewAvailable 后端门禁
* @returns 正式质量摘要
*/
function review(status: EffectiveKeyframeQualityStatus, manualReviewAvailable = false) {
return {
shotId: 's',
keyframeId: 'k',
qualityDecision: 'passed',
effectiveQualityStatus: status,
manualReviewAvailable,
validationTaskId: 't',
historicalGazePreview: [],
manualReview: null
}
}
/** 模拟已完成机器任务的历史原件。 */
const historical = { id: 't', executionId: 'e', status: 'completed', output: { passed: true }, createdAt: '2026-11-07' }
/** 完整的隔离执行记录,用于验证终态和归属。 */
const execution = {
id: 'e',
projectId: 'p',
workflowName: 'shot-keyframe-validation',
status: 'running',
metadata: { shotId: 's', keyframeId: 'k' },
updatedAt: '2026-11-07T00:00:00Z'
}
/** 仅在内存发送消息的 SSE,不连接真实服务。 */
class MockEvents {
/** 已注册的消息接收器。 */ listener?: (event: { data: string }) => void
/** 本例所有连接。 */ static instances: MockEvents[] = []
constructor() {
MockEvents.instances.push(this)
}
/**
* 注册模拟消息。
* @param name 消息名称
* @param callback 接收器
*/
addEventListener(name: string, callback: (event: { data: string }) => void) {
if (name === 'message') this.listener = callback
}
/** 关闭只清理模拟句柄。 */ close() {}
/**
* 发送测试记录。
* @param record 隔离执行快照
*/
send(record: unknown) {
this.listener?.({ data: JSON.stringify(record) })
}
}
describe('首帧当前有效质量', () => {
it.each([
'stale',
'blocked',
'passed',
'unknown',
'failed',
'needs_review',
'insufficient_evidence',
'manual_accepted'
] as const)('卡片采用当前 %s,不采用历史 Passed 或生成成功', async status => {
vi.stubGlobal(
'fetch',
vi.fn(async url => response(String(url).includes('/quality-review') ? review(status) : []))
)
const wrapper = mount(KeyframeCard, {
props: {
item: { id: 'k', shotId: 's', status: 'completed', imageUrl: '/mock.png' } as ShotKeyframe,
projectId: 'p',
shotId: 's',
shotNo: 1,
stale: false,
blocked: false,
validationPassed: true,
confirming: false
}
})
unmount = () => wrapper.unmount()
await flushPromises()
const labels = {
stale: '审核来源过期',
blocked: '质量受阻',
passed: '质量通过',
unknown: '质量待确认',
failed: '质量未通过',
needs_review: '待人工复核',
insufficient_evidence: '审核证据不足',
manual_accepted: '人工已接受'
}
expect(wrapper.text()).toContain(labels[status])
expect(wrapper.text().includes('设为主首帧')).toBe(['passed', 'manual_accepted'].includes(status))
expect(wrapper.text().includes('质量通过')).toBe(status === 'passed')
})
it.each([
['needs_review', true],
['needs_review', false],
['blocked', false],
['stale', false],
['unknown', false]
] as const)('人工接受按服务端 %s / %s 展示', async (status, allowed) => {
vi.stubGlobal(
'fetch',
vi.fn(async url => response(String(url).includes('/quality-review') ? review(status, allowed) : []))
)
const wrapper = mount(KeyframeValidationHistory, {
props: { projectId: 'p', shotId: 's', keyframeId: 'k', initialOpen: true }
})
unmount = () => wrapper.unmount()
await flushPromises()
expect(wrapper.findAll('button').some(button => button.text() === '人工接受')).toBe(allowed)
expect(wrapper.text()).toContain('历史机器结论:质量通过')
})
it('当前质量刷新失败撤销旧通过和人工门禁,不使用缓存结论', async () => {
const fetcher = vi.fn<typeof fetch>().mockImplementation(async () => response(review('passed', true)))
vi.stubGlobal('fetch', fetcher)
const quality = scope.run(() =>
useEffectiveKeyframeQuality(ref(JSON.stringify(['s', 'k', 'p'])), useKeyframeVision(ref('')))
)!
await flushPromises()
expect(quality.status.value).toBe('passed')
fetcher.mockRejectedValue(new Error('隔离网络失败'))
const refresh = quality.refresh()
expect(quality.status.value).toBe('unknown')
expect(quality.manualReviewAvailable.value).toBe(false)
await refresh
expect(quality.status.value).toBe('unknown')
expect(quality.data.value?.qualityDecision).toBe('passed')
})
it('切换候选清除已打开的人工接受表单,旧表单不能提交', async () => {
const fetcher = vi.fn<typeof fetch>(async url =>
response(
String(url).includes('/quality-review')
? String(url).includes('/k2/')
? { ...review('blocked'), keyframeId: 'k2' }
: review('needs_review', true)
: []
)
)
vi.stubGlobal('fetch', fetcher)
const wrapper = mount(KeyframeValidationHistory, {
props: { projectId: 'p', shotId: 's', keyframeId: 'k', initialOpen: true }
})
unmount = () => wrapper.unmount()
await flushPromises()
await wrapper
.findAll('button')
.find(button => button.text() === '人工接受')!
.trigger('click')
expect(wrapper.text()).toContain('确认接受')
await wrapper.setProps({ keyframeId: 'k2' })
await flushPromises()
expect(wrapper.text()).toContain('质量受阻')
expect(wrapper.text()).not.toContain('确认接受')
expect(fetcher.mock.calls.every(([, options]) => options?.method !== 'POST')).toBe(true)
})
it('项目、镜头、候选及来源变化取消旧请求,迟到响应不回填', async () => {
const pending: Array<{ signal?: AbortSignal | null; resolve: (value: Response) => void }> = []
vi.stubGlobal(
'fetch',
vi.fn((url, options) =>
String(url).includes('/quality-review')
? new Promise<Response>(resolve => pending.push({ signal: options?.signal, resolve }))
: Promise.resolve(response([]))
)
)
const key = ref(JSON.stringify(['s', 'k', 'p', 'source-1']))
const quality = scope.run(() => useEffectiveKeyframeQuality(key, useKeyframeVision(ref(''))))!
for (const next of [
['s', 'k', 'other'],
['s2', 'k', 'other'],
['s2', 'k2', 'other'],
['s2', 'k2', 'other', 'source-2']
]) {
key.value = JSON.stringify(next)
await flushPromises()
}
expect(pending.slice(0, -1).every(item => item.signal?.aborted)).toBe(true)
pending.at(-1)!.resolve(response({ ...review('stale'), shotId: 's2', keyframeId: 'k2' }))
await flushPromises()
for (const item of pending.slice(0, -1)) item.resolve(response(review('passed')))
await flushPromises()
expect(quality.status.value).toBe('stale')
})
it('SSE 终态回读当前接口,拒绝错候选和旧项目事件', async () => {
MockEvents.instances = []
vi.stubGlobal('EventSource', MockEvents)
let status: EffectiveKeyframeQualityStatus = 'stale'
const fetcher = vi.fn<typeof fetch>(async url =>
response(
String(url).includes('/quality-review')
? review(status)
: String(url).includes('/validations')
? [historical]
: execution
)
)
vi.stubGlobal('fetch', fetcher)
const key = ref(JSON.stringify(['s', 'k', 'p']))
const quality = scope.run(() => useEffectiveKeyframeQuality(key, useKeyframeVision(key)))!
await flushPromises()
expect(quality.status.value).toBe('stale')
const events = MockEvents.instances.at(-1)!
const count = fetcher.mock.calls.length
events.send({ ...execution, status: 'completed', metadata: { keyframeId: 'wrong' } })
await flushPromises()
expect(fetcher.mock.calls.length).toBe(count)
status = 'passed'
events.send({ ...execution, status: 'completed', updatedAt: '2026-11-07T00:01:00Z', result: { passed: false } })
await flushPromises()
expect(quality.status.value).toBe('passed')
key.value = ''
await flushPromises()
events.send({ ...execution, status: 'completed' })
await flushPromises()
expect(quality.status.value).toBe('unknown')
expect(
fetcher.mock.calls.every(([, options]) => !['POST', 'PUT', 'DELETE'].includes(options?.method ?? 'GET'))
).toBe(true)
})
it('接口携带转义后的项目范围和取消信号', async () => {
const fetcher = vi.fn<typeof fetch>(async () => response(review('unknown')))
vi.stubGlobal('fetch', fetcher)
await qualityApi.keyframeQualityReview('s/a', 'k/b', new AbortController().signal, 'p/c')
expect(fetcher.mock.calls[0]?.[0]).toBe(
'/api/storyboard-shots/s%2Fa/keyframes/k%2Fb/quality-review?projectId=p%2Fc'
)
})
it('结果组件不把同步历史 Passed 显示为当前通过', () => {
const wrapper = mount(QualityResult, {
props: {
currentStatus: 'stale',
receipt: {
kind: 'keyframe',
result: {
shotId: 's',
keyframeId: 'k',
validationTaskId: 't',
imageUrl: '',
isPrimary: false,
passed: true,
summary: '原审核摘要',
issues: [],
subjects: [],
subjectCountConsistent: true,
unauthorizedText: { detected: false, texts: [] }
}
}
}
})
unmount = () => wrapper.unmount()
expect(wrapper.text()).toContain('审核来源过期')
expect(wrapper.text()).not.toContain('视觉校验通过')
})
})