Files
short-drama-agent-front/tests/features/production/source-review.test.ts
T

279 lines
11 KiB
TypeScript

import { effectScope, ref } from 'vue'
import { flushPromises } from '@vue/test-utils'
import { afterEach, expect, it, vi } from 'vitest'
import { useSourceReview } from '@/features/production/useSourceReview'
import { sourceReviewApi, type SourceReviewPreview, type SourceVisionPlan } from '@/features/production/source-review'
/** 全部请求仅使用隔离数据,不连接 Provider。 */
const hash = 'a'.repeat(64)
/** 原输入和当前参考完整公开证据。 */
const input = {
fingerprint: hash,
sourceFingerprint: hash,
provider: 'mock',
model: 'mock',
providerPrompt: '历史描述',
generationOptions: {},
references: [
{
imageNumber: 1,
bindings: [
{ role: 'layout-master', subjectRef: '@SC1' },
{ role: 'scene-form', subjectRef: '@SC2' }
]
}
]
}
/** 可复用隔离预检。 */
export const sourcePreview: SourceReviewPreview = {
projectId: 'p',
shotId: 's',
keyframeId: 'k',
imageUrl: '',
fingerprint: hash,
originalPixels: { sha256: hash },
originalInputFingerprint: hash,
originalProviderInput: input,
sourceChanges: {},
historicalVision: [],
references: [{ imageNumber: 1, imageId: 'i', imageUrl: '' }],
currentReferenceInput: input
}
/** 精确机器计划。 */
export const sourcePlan: SourceVisionPlan = {
reviewId: 'r',
reviewFingerprint: hash,
originalInputFingerprint: hash,
referenceInputFingerprint: hash,
sourceFingerprint: hash,
requestFingerprint: hash,
imageSha256: hash,
model: 'mock',
routeFingerprint: hash,
steps: ['general', 'physical']
}
/** 每次隔离作用域。 */
let scope = effectScope()
afterEach(() => {
scope.stop()
scope = effectScope()
sessionStorage.clear()
vi.unstubAllGlobals()
})
/**
* 创建只处理正式路径的 Mock。
* @param status 人工原状态
* @returns 请求记录
*/
export function sourceMock(status = 'passed') {
const calls: Array<{ url: string; body: Record<string, unknown> | null }> = []
const record = {
reviewId: 'r',
current: true,
invalidation: null,
review: {
expectedFingerprint: hash,
reviewer: '审核人',
reason: '理由',
observations: [
{
imageNumber: 1,
finding: {
identity: 'passed',
structure: 'passed',
spatial: 'passed',
action: 'passed',
continuity: 'passed'
},
note: '可见'
}
]
},
originalResult: { status, evidenceKind: 'manual-source-observation' },
reviewStatus: status === 'insufficient_evidence' ? 'needs_review' : status
}
const fetcher = vi.fn<typeof fetch>(async (url, init) => {
const path = String(url)
const body = init?.body ? JSON.parse(String(init.body)) : null
calls.push({ url: path, body })
let data: unknown
if (path.includes('/source-review/preview')) data = sourcePreview
else if (path.endsWith('/source-reviews')) data = { reviewId: 'r' }
else if (path.endsWith('/vision/preview')) data = sourcePlan
else if (path.endsWith('/vision/authorizations')) data = { authorizationId: 'auth', plan: sourcePlan }
else if (path.endsWith('/source-reviews/r')) data = record
else if (path.includes('/quality-review'))
data = { shotId: 's', keyframeId: 'k', effectiveQualityStatus: 'stale', manualReviewAvailable: false }
else if (path.includes('/validations')) data = []
else return new Response(JSON.stringify({ error: { message: '未模拟请求' } }), { status: 404 })
return new Response(JSON.stringify({ data }))
})
return { calls, fetcher, record }
}
/** 默认未知且逐图保存,人工通过不自动批准或执行。 */
it('默认未知,逐图包含全部职责;原人工状态不覆盖', async () => {
const mock = sourceMock('insufficient_evidence')
vi.stubGlobal('fetch', mock.fetcher)
const form = scope.run(() => useSourceReview(ref(JSON.stringify(['s', 'k', 'p']))))!
await flushPromises()
await form.loadPreview()
expect(Object.values(form.observations.value[0]!.finding)).toEqual(Array(5).fill('unknown'))
expect(form.preview.value?.currentReferenceInput.references[0]?.bindings).toHaveLength(2)
form.reviewer.value = '审核人'
form.reason.value = '理由'
form.observations.value[0]!.note = '门轴看不清'
await form.save()
expect(form.record.value?.reviewStatus).toBe('needs_review')
expect(form.record.value?.originalResult.status).toBe('insufficient_evidence')
await form.loadPlan()
expect(mock.calls.filter(c => c.url.endsWith('/vision/preview'))).toHaveLength(0)
expect(mock.calls.filter(c => c.url.endsWith('/vision') || c.url.endsWith('/authorizations'))).toHaveLength(0)
})
/** 批准与执行分步;变更费用撤销原授权。 */
it('真实费用材料独立批准,变更范围撤销授权,不自动收费', async () => {
const mock = sourceMock()
vi.stubGlobal('fetch', mock.fetcher)
const form = scope.run(() => useSourceReview(ref(JSON.stringify(['s', 'k', 'p']))))!
await flushPromises()
form.reviewId.value = 'r'
await form.readRecord()
await form.loadPlan()
form.approvedBy.value = '批准人'
form.operator.value = '操作人'
form.approvalSha256.value = hash
form.estimatedMin.value = 1
form.estimatedMax.value = 2
form.approved.value = true
await form.authorize()
expect(form.authorizationId.value).toBe('auth')
const body = mock.calls.find(c => c.url.endsWith('/authorizations'))!.body!
expect(body.feeScope).toEqual({ currency: 'CNY', estimatedMin: 1, estimatedMax: 2, maxRequests: 2 })
expect(mock.calls.some(c => c.url.endsWith('/vision'))).toBe(false)
form.estimatedMax.value = 3
expect(form.authorizationId.value).toBe('')
})
/** 项目切换后不接收旧预检。 */
it('旧项目迟到响应被忽略', async () => {
const mock = sourceMock()
let finish!: (value: Response) => void
vi.stubGlobal(
'fetch',
vi.fn<typeof fetch>((url, init) =>
String(url).includes('/source-review/preview')
? new Promise(resolve => {
finish = resolve
})
: mock.fetcher(url, init)
)
)
const key = ref(JSON.stringify(['s', 'k', 'p']))
const form = scope.run(() => useSourceReview(key))!
await flushPromises()
const pending = form.loadPreview()
key.value = JSON.stringify(['s2', 'k2', 'p2'])
finish(new Response(JSON.stringify({ data: sourcePreview })))
await pending
expect(form.preview.value).toBeNull()
})
/** 执行请求仅携带本次授权和明确原任务指纹。 */
it('执行和恢复使用正式路径,不能混入模型或文字参数', async () => {
const fetcher = vi.fn<typeof fetch>(async () => new Response(JSON.stringify({ data: {} })))
vi.stubGlobal('fetch', fetcher)
await sourceReviewApi.execute('p/a', 'r/b', {
authorizationId: 'auth',
resume: { resumeValidationTaskId: 'task', expectedRequestFingerprint: hash }
})
expect(String(fetcher.mock.calls[0]![0])).toBe(
'/api/projects/p%2Fa/storyboard-keyframes/source-reviews/r%2Fb/vision'
)
expect(JSON.parse(String(fetcher.mock.calls[0]![1]?.body))).toEqual({
authorizationId: 'auth',
resume: { resumeValidationTaskId: 'task', expectedRequestFingerprint: hash }
})
})
/** 并发点击仅一次送出,断线费用未知不重发。 */
it('并发和未知费用保持同一候选提交保护', async () => {
const { submitSourceVision } = await import('@/features/production/keyframe-vision')
const key = JSON.stringify(['source-s', 'source-k', 'source-p'])
let fail!: (cause: Error) => void
const send = vi.fn<() => Promise<never>>(
() =>
new Promise((_, reject) => {
fail = reject
})
)
const first = submitSourceVision(key, [], send)
await expect(submitSourceVision(key, [], send)).rejects.toThrow('费用待核查')
fail(new Error('断线'))
await expect(first).rejects.toThrow('断线')
await expect(submitSourceVision(key, [], send)).rejects.toThrow('费用待核查')
expect(send).toHaveBeenCalledTimes(1)
})
/** 别的主图记录只能追溯,不可签发计划。 */
it('记录与主图指纹不同不会取得机器计划', async () => {
const mock = sourceMock()
mock.record.review.expectedFingerprint = 'b'.repeat(64)
vi.stubGlobal('fetch', mock.fetcher)
const form = scope.run(() => useSourceReview(ref(JSON.stringify(['s', 'k', 'p']))))!
await flushPromises()
form.reviewId.value = 'r'
await form.readRecord()
await form.loadPlan()
expect(form.record.value?.originalResult.status).toBe('passed')
expect(form.targetMatched.value).toBe(false)
expect(form.plan.value).toBeNull()
expect(mock.calls.some(c => c.url.endsWith('/vision/preview'))).toBe(false)
})
/** 完成的失败结论也是完整结果,返回后不自动再提交。 */
it('200 失败结论保持原失败且结算提交观察', async () => {
const { submitSourceVision } = await import('@/features/production/keyframe-vision')
const failed = {
shotId: 's',
keyframeId: 'k',
validationTaskId: 'task',
imageUrl: '',
isPrimary: true,
passed: false,
summary: '结构未通过',
subjectCountConsistent: true,
subjects: [],
issues: [],
unauthorizedText: { detected: false, texts: [] },
qualityDecision: 'failed' as const
}
const send = vi.fn<() => Promise<typeof failed>>(async () => failed)
const result = await submitSourceVision(JSON.stringify(['s', 'k', 'p']), [], send)
expect(result).toEqual(failed)
expect(result).toHaveProperty('passed', false)
expect(send).toHaveBeenCalledTimes(1)
})
/** 实际组件不自动预检、批准或执行,观察控件初始未知。 */
it('抽屉使用真实表单,打开只读历史,免费预检逐项展示全部参考', async () => {
const { mount } = await import('@vue/test-utils')
const Drawer = (await import('@/features/production/components/SourceReviewDrawer.vue')).default
const mock = sourceMock()
vi.stubGlobal('fetch', mock.fetcher)
const wrapper = mount(Drawer, {
props: { open: true, projectId: 'p', shotId: 's', keyframeId: 'k' },
global: { stubs: { AppDrawer: { template: '<div><slot/><slot name="footer"/></div>' }, AssetImage: true } }
})
try {
await flushPromises()
expect(mock.calls.every(c => c.body === null)).toBe(true)
await wrapper
.findAll('button')
.find(b => b.text() === '免费预检当前来源')!
.trigger('click')
await flushPromises()
expect(wrapper.text()).toContain('未知/无法看清')
expect(wrapper.text()).toContain('本次新参考与逐图观察')
expect(wrapper.text()).toContain('@SC1')
expect(wrapper.text()).toContain('@SC2')
expect(wrapper.text()).not.toContain('登记本次费用批准')
} finally {
wrapper.unmount()
}
})