212 lines
9.0 KiB
TypeScript
212 lines
9.0 KiB
TypeScript
import { afterEach, describe, expect, it, vi } from 'vitest'
|
|
import { defineComponent, ref } from 'vue'
|
|
import { mount, flushPromises, type VueWrapper } from '@vue/test-utils'
|
|
import {
|
|
usdToMicros,
|
|
formatMicros,
|
|
imageChargeEligibility,
|
|
imageRequestBlockReason
|
|
} from '@/features/image-authorization/model'
|
|
import { imageAuthorizationApi } from '@/features/image-authorization/api'
|
|
import { useImageGenerationPreview, type ImageGenerationSubmission } from '@/features/subject-images/generation-preview'
|
|
import { ApiError, errorMessage } from '@/lib/http'
|
|
import { imageAuthorizationsFixture } from '../../fixtures/billing'
|
|
import { imagePreviewFixture } from '../../fixtures/image-preview'
|
|
|
|
/** 每个用例清理表单、费用标记及替身。 */
|
|
let wrapper: VueWrapper | undefined
|
|
afterEach(() => {
|
|
wrapper?.unmount()
|
|
sessionStorage.clear()
|
|
vi.restoreAllMocks()
|
|
})
|
|
/**
|
|
* 挂载真实共用生成逻辑,只模拟正式读写接口。
|
|
* @returns 真实表单、用户选择与无费用生成替身
|
|
*/
|
|
function setup() {
|
|
const open = ref(true),
|
|
provider = ref('openai-image'),
|
|
project = ref('billing-project')
|
|
const list = imageAuthorizationsFixture()
|
|
vi.spyOn(imageAuthorizationApi, 'list').mockResolvedValue(list)
|
|
const authorizationPreview = vi.spyOn(imageAuthorizationApi, 'preview').mockImplementation(async () => ({
|
|
provider: provider.value,
|
|
model: 'gpt-image-2.5-flare',
|
|
context: {
|
|
projectId: project.value,
|
|
scope: 'keyframe',
|
|
targetId: 'shot',
|
|
sourceFingerprint: 'c'.repeat(64)
|
|
},
|
|
planFingerprint: 'b'.repeat(64),
|
|
request: {},
|
|
currency: 'USD',
|
|
billingBasis: 'provider_usage',
|
|
hardProviderCostCap: false,
|
|
authorization: list
|
|
}))
|
|
const generate = vi.fn<() => Promise<ImageGenerationSubmission>>(async () => ({ accepted: true }))
|
|
const load = vi.fn<() => Promise<ReturnType<typeof imagePreviewFixture>>>(async () => ({
|
|
...imagePreviewFixture(),
|
|
provider: provider.value,
|
|
model: 'gpt-image-2.5-flare'
|
|
}))
|
|
let flow!: ReturnType<typeof useImageGenerationPreview>
|
|
wrapper = mount(
|
|
defineComponent({
|
|
setup() {
|
|
flow = useImageGenerationPreview({
|
|
open,
|
|
target: () => project.value + ':shot',
|
|
recoveryTarget: () => 'keyframe:shot',
|
|
chargeContext: () => ({
|
|
projectId: project.value,
|
|
targetId: 'shot',
|
|
scope: 'keyframe',
|
|
exactPreview: true
|
|
}),
|
|
input: () => ({ provider: provider.value, generationOptions: {} }),
|
|
disabled: () => false,
|
|
load,
|
|
generate
|
|
})
|
|
return () => null
|
|
}
|
|
})
|
|
)
|
|
return { flow, provider, project, list, generate, load, authorizationPreview }
|
|
}
|
|
|
|
describe('OpenAI 图片有限授权及收费门禁', () => {
|
|
it('美元精确转换,未知金额不显示零,拒绝过多小数与非法金额', () => {
|
|
expect(usdToMicros('0.123456')).toBe(123456)
|
|
expect(usdToMicros('5')).toBe(5_000_000)
|
|
for (const value of ['', '0', '-1', '1e2', '0.0000001', 'Infinity']) expect(usdToMicros(value)).toBeNull()
|
|
expect(formatMicros(null)).toBe('未知')
|
|
expect(formatMicros(0)).toBe('USD 0')
|
|
})
|
|
it.each(['expired', 'revoked', 'budget', 'requests', 'scope', 'model', 'target'] as const)(
|
|
'%s 不授予新收费资格',
|
|
kind => {
|
|
const list = imageAuthorizationsFixture(),
|
|
row = list.authorizations[0]!
|
|
if (kind === 'expired') {
|
|
row.expired = true
|
|
row.input.expiresAt = '2000-01-01T00:00:00Z'
|
|
}
|
|
if (kind === 'revoked') row.status = 'revoked'
|
|
if (kind === 'budget') row.remainingMicros = row.input.perRequestMicros - 1
|
|
if (kind === 'requests') row.remainingRequests = 0
|
|
if (kind === 'scope') row.input.scopes = ['identity']
|
|
if (kind === 'model') row.input.models = ['other']
|
|
if (kind === 'target') row.input.targetIds = ['other']
|
|
expect(imageChargeEligibility(list, 'keyframe', 'shot', 'gpt-image-2.5-flare').allowed).toBe(false)
|
|
}
|
|
)
|
|
it('有效持续授权无需逐图批准,仍要求原图片预览并防止双击', async () => {
|
|
const { flow, generate } = setup()
|
|
expect(flow.canSubmit.value).toBe(false)
|
|
await flow.loadPreview()
|
|
expect(flow.requiresCostConfirmation.value).toBe(false)
|
|
expect(flow.acknowledged.value).toBe(false)
|
|
expect(flow.canSubmit.value).toBe(true)
|
|
await Promise.all([flow.submit(), flow.submit()])
|
|
expect(generate).toHaveBeenCalledExactlyOnceWith({
|
|
provider: 'openai-image',
|
|
generationOptions: {},
|
|
expectedPreviewFingerprint: 'a'.repeat(64)
|
|
})
|
|
})
|
|
it('切换供应方立即撤销原预览,重新预览后必须独立确认', async () => {
|
|
const { flow, provider, generate } = setup()
|
|
await flow.loadPreview()
|
|
provider.value = 'qwen-image'
|
|
expect(flow.preview.value).toBeNull()
|
|
await flow.loadPreview()
|
|
expect(flow.requiresCostConfirmation.value).toBe(true)
|
|
await flow.submit()
|
|
expect(generate).not.toHaveBeenCalled()
|
|
flow.acknowledged.value = true
|
|
await flow.submit()
|
|
expect(generate).toHaveBeenCalledOnce()
|
|
})
|
|
it('未知费用禁止重试;完整同计划在撤销、到期及项目阻断后仍可免费复用', async () => {
|
|
const { flow, list, generate } = setup()
|
|
list.billingBlocked = true
|
|
await flow.loadPreview()
|
|
await flow.submit()
|
|
expect(generate).not.toHaveBeenCalled()
|
|
const grant = list.authorizations[0]!
|
|
grant.expired = true
|
|
grant.status = 'revoked'
|
|
list.requests.push({
|
|
id: 'old-request',
|
|
status: 'completed',
|
|
input: {
|
|
projectId: 'billing-project',
|
|
scope: 'keyframe',
|
|
targetId: 'shot',
|
|
candidateId: 'old-candidate',
|
|
authorizationId: 'grant',
|
|
provider: 'openai-image',
|
|
model: 'gpt-image-2.5-flare',
|
|
sourceFingerprint: 'c'.repeat(64),
|
|
planFingerprint: 'b'.repeat(64),
|
|
reservedMicros: 500_000,
|
|
request: {}
|
|
},
|
|
output: { usageCostMicros: null, actualBilledMicros: null, result: { image: 'mock' } }
|
|
})
|
|
await flow.loadPreview()
|
|
expect(flow.chargeNotice.value).toContain('免费复用')
|
|
await flow.submit()
|
|
expect(generate).toHaveBeenCalledOnce()
|
|
expect(list.authorizations[0]!.usedRequests).toBe(0)
|
|
const original = list.requests[0]!
|
|
expect(imageRequestBlockReason(original)).toContain('缺少可核验的用量')
|
|
original.output!.usageCostMicros = original.input.reservedMicros + 1
|
|
expect(imageRequestBlockReason(original)).toContain('超过单次预留')
|
|
original.status = 'running'
|
|
expect(imageRequestBlockReason(original)).toContain('禁止重发')
|
|
original.status = 'unknown'
|
|
original.output!.error = { failureType: 'rate_limited' }
|
|
expect(imageRequestBlockReason(original)).toContain('限流')
|
|
})
|
|
it('并发额度拒绝后需重新读取授权,刷新及重新挂载均不重复生成', async () => {
|
|
const { flow, list, generate, project } = setup()
|
|
generate.mockResolvedValueOnce({
|
|
accepted: false,
|
|
cause: new ApiError('额度不足', 409, undefined, 'IMAGE_AUTHORIZATION_BUDGET_EXCEEDED')
|
|
} as { accepted: boolean })
|
|
await flow.loadPreview()
|
|
await flow.submit()
|
|
expect(flow.canSubmit.value).toBe(false)
|
|
list.authorizations[0]!.remainingMicros = 0
|
|
await flow.loadPreview()
|
|
await flow.submit()
|
|
project.value = 'other-project'
|
|
await flushPromises()
|
|
expect(flow.preview.value).toBeNull()
|
|
expect(generate).toHaveBeenCalledOnce()
|
|
})
|
|
it('错误区分计费配额与限流、未知回执及供应方切换', () => {
|
|
expect(
|
|
errorMessage(new ApiError('429', 502, { failureType: 'rate_limited' }, 'OPENAI_IMAGE_PROVIDER_ERROR'))
|
|
).toContain('限流')
|
|
expect(
|
|
errorMessage(
|
|
new ApiError('429', 502, { failureType: 'billing_quota_exceeded' }, 'OPENAI_IMAGE_PROVIDER_ERROR')
|
|
)
|
|
).toContain('计费配额')
|
|
expect(
|
|
errorMessage(
|
|
new ApiError('unknown', 502, { failureType: 'receipt_unknown' }, 'OPENAI_IMAGE_RECEIPT_INVALID')
|
|
)
|
|
).toContain('禁止重试')
|
|
expect(errorMessage(new ApiError('switch', 409, undefined, 'IMAGE_PROVIDER_CONFIRMATION_REQUIRED'))).toContain(
|
|
'主动选择'
|
|
)
|
|
})
|
|
})
|