feat: initial release v0.3.0
This commit is contained in:
396
tests/integration/api/contract/crud-routes.test.ts
Normal file
396
tests/integration/api/contract/crud-routes.test.ts
Normal file
@@ -0,0 +1,396 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { ROUTE_CATALOG } from '../../../contracts/route-catalog'
|
||||
import { buildMockRequest } from '../../../helpers/request'
|
||||
|
||||
type RouteMethod = 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE'
|
||||
|
||||
type AuthState = {
|
||||
authenticated: boolean
|
||||
}
|
||||
|
||||
type RouteContext = {
|
||||
params: Promise<Record<string, string>>
|
||||
}
|
||||
|
||||
const authState = vi.hoisted<AuthState>(() => ({
|
||||
authenticated: false,
|
||||
}))
|
||||
|
||||
const prismaMock = vi.hoisted(() => ({
|
||||
globalCharacter: {
|
||||
findUnique: vi.fn(),
|
||||
update: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
},
|
||||
globalAssetFolder: {
|
||||
findUnique: vi.fn(),
|
||||
},
|
||||
characterAppearance: {
|
||||
findUnique: vi.fn(),
|
||||
update: vi.fn(),
|
||||
},
|
||||
novelPromotionLocation: {
|
||||
findUnique: vi.fn(),
|
||||
update: vi.fn(),
|
||||
},
|
||||
locationImage: {
|
||||
updateMany: vi.fn(),
|
||||
update: vi.fn(),
|
||||
},
|
||||
novelPromotionClip: {
|
||||
update: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/api-auth', () => {
|
||||
const unauthorized = () => new Response(
|
||||
JSON.stringify({ error: { code: 'UNAUTHORIZED' } }),
|
||||
{ status: 401, headers: { 'content-type': 'application/json' } },
|
||||
)
|
||||
|
||||
return {
|
||||
isErrorResponse: (value: unknown) => value instanceof Response,
|
||||
requireUserAuth: async () => {
|
||||
if (!authState.authenticated) return unauthorized()
|
||||
return { session: { user: { id: 'user-1' } } }
|
||||
},
|
||||
requireProjectAuth: async (projectId: string) => {
|
||||
if (!authState.authenticated) return unauthorized()
|
||||
return {
|
||||
session: { user: { id: 'user-1' } },
|
||||
project: { id: projectId, userId: 'user-1', mode: 'novel-promotion' },
|
||||
}
|
||||
},
|
||||
requireProjectAuthLight: async (projectId: string) => {
|
||||
if (!authState.authenticated) return unauthorized()
|
||||
return {
|
||||
session: { user: { id: 'user-1' } },
|
||||
project: { id: projectId, userId: 'user-1', mode: 'novel-promotion' },
|
||||
}
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@/lib/prisma', () => ({
|
||||
prisma: prismaMock,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/storage', () => ({
|
||||
getSignedUrl: vi.fn((key: string) => `https://signed.example/${key}`),
|
||||
}))
|
||||
|
||||
function toModuleImportPath(routeFile: string): string {
|
||||
return `@/${routeFile.replace(/^src\//, '').replace(/\.ts$/, '')}`
|
||||
}
|
||||
|
||||
function resolveParamValue(paramName: string): string {
|
||||
const key = paramName.toLowerCase()
|
||||
if (key.includes('project')) return 'project-1'
|
||||
if (key.includes('character')) return 'character-1'
|
||||
if (key.includes('location')) return 'location-1'
|
||||
if (key.includes('appearance')) return '0'
|
||||
if (key.includes('episode')) return 'episode-1'
|
||||
if (key.includes('storyboard')) return 'storyboard-1'
|
||||
if (key.includes('panel')) return 'panel-1'
|
||||
if (key.includes('clip')) return 'clip-1'
|
||||
if (key.includes('folder')) return 'folder-1'
|
||||
if (key === 'id') return 'id-1'
|
||||
return `${paramName}-1`
|
||||
}
|
||||
|
||||
function toApiPath(routeFile: string): { path: string; params: Record<string, string> } {
|
||||
const withoutPrefix = routeFile
|
||||
.replace(/^src\/app/, '')
|
||||
.replace(/\/route\.ts$/, '')
|
||||
|
||||
const params: Record<string, string> = {}
|
||||
const path = withoutPrefix.replace(/\[([^\]]+)\]/g, (_full, paramName: string) => {
|
||||
const value = resolveParamValue(paramName)
|
||||
params[paramName] = value
|
||||
return value
|
||||
})
|
||||
return { path, params }
|
||||
}
|
||||
|
||||
function buildGenericBody() {
|
||||
return {
|
||||
id: 'id-1',
|
||||
name: 'Name',
|
||||
type: 'character',
|
||||
userInstruction: 'instruction',
|
||||
characterId: 'character-1',
|
||||
locationId: 'location-1',
|
||||
appearanceId: 'appearance-1',
|
||||
modifyPrompt: 'modify prompt',
|
||||
storyboardId: 'storyboard-1',
|
||||
panelId: 'panel-1',
|
||||
panelIndex: 0,
|
||||
episodeId: 'episode-1',
|
||||
content: 'x'.repeat(140),
|
||||
voicePrompt: 'voice prompt',
|
||||
previewText: 'preview text',
|
||||
referenceImageUrl: 'https://example.com/ref.png',
|
||||
referenceImageUrls: ['https://example.com/ref.png'],
|
||||
lineId: 'line-1',
|
||||
audioModel: 'fal::audio-model',
|
||||
videoModel: 'fal::video-model',
|
||||
insertAfterPanelId: 'panel-1',
|
||||
sourcePanelId: 'panel-2',
|
||||
variant: { video_prompt: 'variant prompt' },
|
||||
currentDescription: 'description',
|
||||
modifyInstruction: 'instruction',
|
||||
currentPrompt: 'prompt',
|
||||
all: false,
|
||||
}
|
||||
}
|
||||
|
||||
async function invokeRouteMethod(
|
||||
routeFile: string,
|
||||
method: RouteMethod,
|
||||
): Promise<Response> {
|
||||
const { path, params } = toApiPath(routeFile)
|
||||
const modulePath = toModuleImportPath(routeFile)
|
||||
const mod = await import(modulePath)
|
||||
const handler = mod[method] as ((req: Request, ctx?: RouteContext) => Promise<Response>) | undefined
|
||||
if (!handler) {
|
||||
throw new Error(`Route ${routeFile} missing method ${method}`)
|
||||
}
|
||||
const req = buildMockRequest({
|
||||
path,
|
||||
method,
|
||||
...(method === 'GET' || method === 'DELETE' ? {} : { body: buildGenericBody() }),
|
||||
})
|
||||
return await handler(req, { params: Promise.resolve(params) })
|
||||
}
|
||||
|
||||
describe('api contract - crud routes (behavior)', () => {
|
||||
const routes = ROUTE_CATALOG.filter(
|
||||
(entry) => entry.contractGroup === 'crud-asset-hub-routes' || entry.contractGroup === 'crud-novel-promotion-routes',
|
||||
)
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
authState.authenticated = false
|
||||
|
||||
prismaMock.globalCharacter.findUnique.mockResolvedValue({
|
||||
id: 'character-1',
|
||||
userId: 'user-1',
|
||||
})
|
||||
prismaMock.globalAssetFolder.findUnique.mockResolvedValue({
|
||||
id: 'folder-1',
|
||||
userId: 'user-1',
|
||||
})
|
||||
prismaMock.globalCharacter.update.mockResolvedValue({
|
||||
id: 'character-1',
|
||||
name: 'Alice',
|
||||
userId: 'user-1',
|
||||
appearances: [],
|
||||
})
|
||||
prismaMock.globalCharacter.delete.mockResolvedValue({ id: 'character-1' })
|
||||
prismaMock.characterAppearance.findUnique.mockResolvedValue({
|
||||
id: 'appearance-1',
|
||||
characterId: 'character-1',
|
||||
imageUrls: JSON.stringify(['cos/char-0.png', 'cos/char-1.png']),
|
||||
imageUrl: null,
|
||||
selectedIndex: null,
|
||||
character: { id: 'character-1', name: 'Alice' },
|
||||
})
|
||||
prismaMock.characterAppearance.update.mockResolvedValue({
|
||||
id: 'appearance-1',
|
||||
selectedIndex: 1,
|
||||
imageUrl: 'cos/char-1.png',
|
||||
})
|
||||
prismaMock.novelPromotionLocation.findUnique.mockResolvedValue({
|
||||
id: 'location-1',
|
||||
name: 'Old Town',
|
||||
images: [
|
||||
{ id: 'img-0', imageIndex: 0, imageUrl: 'cos/loc-0.png' },
|
||||
{ id: 'img-1', imageIndex: 1, imageUrl: 'cos/loc-1.png' },
|
||||
],
|
||||
})
|
||||
prismaMock.locationImage.updateMany.mockResolvedValue({ count: 2 })
|
||||
prismaMock.locationImage.update.mockResolvedValue({
|
||||
id: 'img-1',
|
||||
imageIndex: 1,
|
||||
imageUrl: 'cos/loc-1.png',
|
||||
isSelected: true,
|
||||
})
|
||||
prismaMock.novelPromotionLocation.update.mockResolvedValue({
|
||||
id: 'location-1',
|
||||
selectedImageId: 'img-1',
|
||||
})
|
||||
prismaMock.novelPromotionClip.update.mockResolvedValue({
|
||||
id: 'clip-1',
|
||||
characters: JSON.stringify(['Alice']),
|
||||
location: 'Old Town',
|
||||
content: 'clip content',
|
||||
screenplay: JSON.stringify({ scenes: [{ id: 1 }] }),
|
||||
})
|
||||
})
|
||||
|
||||
it('crud route group exists', () => {
|
||||
expect(routes.length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('all crud route methods reject unauthenticated requests (no 2xx pass-through)', async () => {
|
||||
const methods: ReadonlyArray<RouteMethod> = ['GET', 'POST', 'PATCH', 'PUT', 'DELETE']
|
||||
let checkedMethodCount = 0
|
||||
|
||||
for (const entry of routes) {
|
||||
const modulePath = toModuleImportPath(entry.routeFile)
|
||||
const mod = await import(modulePath)
|
||||
for (const method of methods) {
|
||||
if (typeof mod[method] !== 'function') continue
|
||||
checkedMethodCount += 1
|
||||
const res = await invokeRouteMethod(entry.routeFile, method)
|
||||
expect(res.status, `${entry.routeFile}#${method} should reject unauthenticated`).toBeGreaterThanOrEqual(400)
|
||||
expect(res.status, `${entry.routeFile}#${method} should not be server-error on auth gate`).toBeLessThan(500)
|
||||
}
|
||||
}
|
||||
|
||||
expect(checkedMethodCount).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('PATCH /asset-hub/characters/[characterId] writes normalized fields to prisma.globalCharacter.update', async () => {
|
||||
authState.authenticated = true
|
||||
const mod = await import('@/app/api/asset-hub/characters/[characterId]/route')
|
||||
const req = buildMockRequest({
|
||||
path: '/api/asset-hub/characters/character-1',
|
||||
method: 'PATCH',
|
||||
body: {
|
||||
name: ' Alice ',
|
||||
aliases: ['A'],
|
||||
profileConfirmed: true,
|
||||
folderId: 'folder-1',
|
||||
},
|
||||
})
|
||||
|
||||
const res = await mod.PATCH(req, { params: Promise.resolve({ characterId: 'character-1' }) })
|
||||
expect(res.status).toBe(200)
|
||||
expect(prismaMock.globalCharacter.update).toHaveBeenCalledWith(expect.objectContaining({
|
||||
where: { id: 'character-1' },
|
||||
data: expect.objectContaining({
|
||||
name: 'Alice',
|
||||
aliases: ['A'],
|
||||
profileConfirmed: true,
|
||||
folderId: 'folder-1',
|
||||
}),
|
||||
}))
|
||||
})
|
||||
|
||||
it('DELETE /asset-hub/characters/[characterId] deletes owned character and blocks non-owner', async () => {
|
||||
authState.authenticated = true
|
||||
const mod = await import('@/app/api/asset-hub/characters/[characterId]/route')
|
||||
|
||||
prismaMock.globalCharacter.findUnique.mockResolvedValueOnce({
|
||||
id: 'character-1',
|
||||
userId: 'user-1',
|
||||
})
|
||||
const okReq = buildMockRequest({
|
||||
path: '/api/asset-hub/characters/character-1',
|
||||
method: 'DELETE',
|
||||
})
|
||||
const okRes = await mod.DELETE(okReq, { params: Promise.resolve({ characterId: 'character-1' }) })
|
||||
expect(okRes.status).toBe(200)
|
||||
expect(prismaMock.globalCharacter.delete).toHaveBeenCalledWith({ where: { id: 'character-1' } })
|
||||
|
||||
prismaMock.globalCharacter.findUnique.mockResolvedValueOnce({
|
||||
id: 'character-1',
|
||||
userId: 'other-user',
|
||||
})
|
||||
const forbiddenReq = buildMockRequest({
|
||||
path: '/api/asset-hub/characters/character-1',
|
||||
method: 'DELETE',
|
||||
})
|
||||
const forbiddenRes = await mod.DELETE(forbiddenReq, { params: Promise.resolve({ characterId: 'character-1' }) })
|
||||
expect(forbiddenRes.status).toBe(403)
|
||||
})
|
||||
|
||||
it('POST /novel-promotion/[projectId]/select-character-image writes selectedIndex and imageUrl key', async () => {
|
||||
authState.authenticated = true
|
||||
const mod = await import('@/app/api/novel-promotion/[projectId]/select-character-image/route')
|
||||
const req = buildMockRequest({
|
||||
path: '/api/novel-promotion/project-1/select-character-image',
|
||||
method: 'POST',
|
||||
body: {
|
||||
characterId: 'character-1',
|
||||
appearanceId: 'appearance-1',
|
||||
selectedIndex: 1,
|
||||
},
|
||||
})
|
||||
|
||||
const res = await mod.POST(req, { params: Promise.resolve({ projectId: 'project-1' }) })
|
||||
expect(res.status).toBe(200)
|
||||
expect(prismaMock.characterAppearance.update).toHaveBeenCalledWith({
|
||||
where: { id: 'appearance-1' },
|
||||
data: {
|
||||
selectedIndex: 1,
|
||||
imageUrl: 'cos/char-1.png',
|
||||
},
|
||||
})
|
||||
|
||||
const payload = await res.json() as { success: boolean; selectedIndex: number; imageUrl: string }
|
||||
expect(payload).toEqual({
|
||||
success: true,
|
||||
selectedIndex: 1,
|
||||
imageUrl: 'https://signed.example/cos/char-1.png',
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /novel-promotion/[projectId]/select-location-image toggles selected state and selectedImageId', async () => {
|
||||
authState.authenticated = true
|
||||
const mod = await import('@/app/api/novel-promotion/[projectId]/select-location-image/route')
|
||||
const req = buildMockRequest({
|
||||
path: '/api/novel-promotion/project-1/select-location-image',
|
||||
method: 'POST',
|
||||
body: {
|
||||
locationId: 'location-1',
|
||||
selectedIndex: 1,
|
||||
},
|
||||
})
|
||||
|
||||
const res = await mod.POST(req, { params: Promise.resolve({ projectId: 'project-1' }) })
|
||||
expect(res.status).toBe(200)
|
||||
expect(prismaMock.locationImage.updateMany).toHaveBeenCalledWith({
|
||||
where: { locationId: 'location-1' },
|
||||
data: { isSelected: false },
|
||||
})
|
||||
expect(prismaMock.locationImage.update).toHaveBeenCalledWith({
|
||||
where: { locationId_imageIndex: { locationId: 'location-1', imageIndex: 1 } },
|
||||
data: { isSelected: true },
|
||||
})
|
||||
expect(prismaMock.novelPromotionLocation.update).toHaveBeenCalledWith({
|
||||
where: { id: 'location-1' },
|
||||
data: { selectedImageId: 'img-1' },
|
||||
})
|
||||
})
|
||||
|
||||
it('PATCH /novel-promotion/[projectId]/clips/[clipId] writes provided editable fields', async () => {
|
||||
authState.authenticated = true
|
||||
const mod = await import('@/app/api/novel-promotion/[projectId]/clips/[clipId]/route')
|
||||
const req = buildMockRequest({
|
||||
path: '/api/novel-promotion/project-1/clips/clip-1',
|
||||
method: 'PATCH',
|
||||
body: {
|
||||
characters: JSON.stringify(['Alice']),
|
||||
location: 'Old Town',
|
||||
content: 'clip content',
|
||||
screenplay: JSON.stringify({ scenes: [{ id: 1 }] }),
|
||||
},
|
||||
})
|
||||
|
||||
const res = await mod.PATCH(req, {
|
||||
params: Promise.resolve({ projectId: 'project-1', clipId: 'clip-1' }),
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
expect(prismaMock.novelPromotionClip.update).toHaveBeenCalledWith({
|
||||
where: { id: 'clip-1' },
|
||||
data: {
|
||||
characters: JSON.stringify(['Alice']),
|
||||
location: 'Old Town',
|
||||
content: 'clip content',
|
||||
screenplay: JSON.stringify({ scenes: [{ id: 1 }] }),
|
||||
},
|
||||
})
|
||||
})
|
||||
})
|
||||
487
tests/integration/api/contract/direct-submit-routes.test.ts
Normal file
487
tests/integration/api/contract/direct-submit-routes.test.ts
Normal file
@@ -0,0 +1,487 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { TASK_TYPE, type TaskType } from '@/lib/task/types'
|
||||
import { buildMockRequest } from '../../../helpers/request'
|
||||
|
||||
type AuthState = {
|
||||
authenticated: boolean
|
||||
projectMode: 'novel-promotion' | 'other'
|
||||
}
|
||||
|
||||
type SubmitResult = {
|
||||
taskId: string
|
||||
async: true
|
||||
}
|
||||
|
||||
type RouteContext = {
|
||||
params: Promise<Record<string, string>>
|
||||
}
|
||||
|
||||
type DirectRouteCase = {
|
||||
routeFile: string
|
||||
body: Record<string, unknown>
|
||||
params?: Record<string, string>
|
||||
expectedTaskType: TaskType
|
||||
expectedTargetType: string
|
||||
expectedProjectId: string
|
||||
}
|
||||
|
||||
const authState = vi.hoisted<AuthState>(() => ({
|
||||
authenticated: true,
|
||||
projectMode: 'novel-promotion',
|
||||
}))
|
||||
|
||||
const submitTaskMock = vi.hoisted(() => vi.fn<(...args: unknown[]) => Promise<SubmitResult>>())
|
||||
|
||||
const configServiceMock = vi.hoisted(() => ({
|
||||
getUserModelConfig: vi.fn(async () => ({
|
||||
characterModel: 'img::character',
|
||||
locationModel: 'img::location',
|
||||
editModel: 'img::edit',
|
||||
})),
|
||||
buildImageBillingPayloadFromUserConfig: vi.fn((input: { basePayload: Record<string, unknown> }) => ({
|
||||
...input.basePayload,
|
||||
generationOptions: { resolution: '1024x1024' },
|
||||
})),
|
||||
getProjectModelConfig: vi.fn(async () => ({
|
||||
characterModel: 'img::character',
|
||||
locationModel: 'img::location',
|
||||
editModel: 'img::edit',
|
||||
storyboardModel: 'img::storyboard',
|
||||
analysisModel: 'llm::analysis',
|
||||
})),
|
||||
buildImageBillingPayload: vi.fn(async (input: { basePayload: Record<string, unknown> }) => ({
|
||||
...input.basePayload,
|
||||
generationOptions: { resolution: '1024x1024' },
|
||||
})),
|
||||
resolveProjectModelCapabilityGenerationOptions: vi.fn(async () => ({
|
||||
resolution: '1024x1024',
|
||||
})),
|
||||
}))
|
||||
|
||||
const hasOutputMock = vi.hoisted(() => ({
|
||||
hasGlobalCharacterOutput: vi.fn(async () => false),
|
||||
hasGlobalLocationOutput: vi.fn(async () => false),
|
||||
hasGlobalCharacterAppearanceOutput: vi.fn(async () => false),
|
||||
hasGlobalLocationImageOutput: vi.fn(async () => false),
|
||||
hasCharacterAppearanceOutput: vi.fn(async () => false),
|
||||
hasLocationImageOutput: vi.fn(async () => false),
|
||||
hasPanelLipSyncOutput: vi.fn(async () => false),
|
||||
hasPanelImageOutput: vi.fn(async () => false),
|
||||
hasPanelVideoOutput: vi.fn(async () => false),
|
||||
hasVoiceLineAudioOutput: vi.fn(async () => false),
|
||||
}))
|
||||
|
||||
const prismaMock = vi.hoisted(() => ({
|
||||
userPreference: {
|
||||
findUnique: vi.fn(async () => ({ lipSyncModel: 'fal::lipsync-model' })),
|
||||
},
|
||||
novelPromotionPanel: {
|
||||
findFirst: vi.fn(async () => ({ id: 'panel-1' })),
|
||||
findMany: vi.fn(async () => []),
|
||||
findUnique: vi.fn(async ({ where }: { where?: { id?: string } }) => {
|
||||
const id = where?.id || 'panel-1'
|
||||
if (id === 'panel-src') {
|
||||
return {
|
||||
id,
|
||||
panelIndex: 1,
|
||||
shotType: 'wide',
|
||||
cameraMove: 'static',
|
||||
description: 'source description',
|
||||
videoPrompt: 'source video prompt',
|
||||
location: 'source location',
|
||||
characters: '[]',
|
||||
srtSegment: '',
|
||||
duration: 3,
|
||||
}
|
||||
}
|
||||
if (id === 'panel-ins') {
|
||||
return {
|
||||
id,
|
||||
panelIndex: 2,
|
||||
shotType: 'medium',
|
||||
cameraMove: 'push',
|
||||
description: 'insert description',
|
||||
videoPrompt: 'insert video prompt',
|
||||
location: 'insert location',
|
||||
characters: '[]',
|
||||
srtSegment: '',
|
||||
duration: 3,
|
||||
}
|
||||
}
|
||||
return {
|
||||
id,
|
||||
panelIndex: 0,
|
||||
shotType: 'medium',
|
||||
cameraMove: 'static',
|
||||
description: 'panel description',
|
||||
videoPrompt: 'panel prompt',
|
||||
location: 'panel location',
|
||||
characters: '[]',
|
||||
srtSegment: '',
|
||||
duration: 3,
|
||||
}
|
||||
}),
|
||||
update: vi.fn(async () => ({})),
|
||||
create: vi.fn(async () => ({ id: 'panel-created', panelIndex: 3 })),
|
||||
},
|
||||
novelPromotionProject: {
|
||||
findUnique: vi.fn(async () => ({
|
||||
id: 'project-data-1',
|
||||
characters: [
|
||||
{ name: 'Narrator', customVoiceUrl: 'https://voice.example/narrator.mp3' },
|
||||
],
|
||||
})),
|
||||
},
|
||||
novelPromotionEpisode: {
|
||||
findFirst: vi.fn(async () => ({
|
||||
id: 'episode-1',
|
||||
speakerVoices: '{}',
|
||||
})),
|
||||
},
|
||||
novelPromotionVoiceLine: {
|
||||
findMany: vi.fn(async () => [
|
||||
{ id: 'line-1', speaker: 'Narrator', content: 'hello world voice line' },
|
||||
]),
|
||||
findFirst: vi.fn(async () => ({
|
||||
id: 'line-1',
|
||||
speaker: 'Narrator',
|
||||
content: 'hello world voice line',
|
||||
})),
|
||||
},
|
||||
$transaction: vi.fn(async (fn: (tx: {
|
||||
novelPromotionPanel: {
|
||||
findMany: (args: unknown) => Promise<Array<{ id: string; panelIndex: number }>>
|
||||
update: (args: unknown) => Promise<unknown>
|
||||
create: (args: unknown) => Promise<{ id: string; panelIndex: number }>
|
||||
}
|
||||
}) => Promise<unknown>) => {
|
||||
const tx = {
|
||||
novelPromotionPanel: {
|
||||
findMany: async () => [],
|
||||
update: async () => ({}),
|
||||
create: async () => ({ id: 'panel-created', panelIndex: 3 }),
|
||||
},
|
||||
}
|
||||
return await fn(tx)
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/api-auth', () => {
|
||||
const unauthorized = () => new Response(
|
||||
JSON.stringify({ error: { code: 'UNAUTHORIZED' } }),
|
||||
{ status: 401, headers: { 'content-type': 'application/json' } },
|
||||
)
|
||||
|
||||
return {
|
||||
isErrorResponse: (value: unknown) => value instanceof Response,
|
||||
requireUserAuth: async () => {
|
||||
if (!authState.authenticated) return unauthorized()
|
||||
return { session: { user: { id: 'user-1' } } }
|
||||
},
|
||||
requireProjectAuth: async (projectId: string) => {
|
||||
if (!authState.authenticated) return unauthorized()
|
||||
return {
|
||||
session: { user: { id: 'user-1' } },
|
||||
project: { id: projectId, userId: 'user-1', mode: authState.projectMode },
|
||||
}
|
||||
},
|
||||
requireProjectAuthLight: async (projectId: string) => {
|
||||
if (!authState.authenticated) return unauthorized()
|
||||
return {
|
||||
session: { user: { id: 'user-1' } },
|
||||
project: { id: projectId, userId: 'user-1', mode: authState.projectMode },
|
||||
}
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@/lib/task/submitter', () => ({
|
||||
submitTask: submitTaskMock,
|
||||
}))
|
||||
vi.mock('@/lib/task/resolve-locale', () => ({
|
||||
resolveRequiredTaskLocale: vi.fn(() => 'zh'),
|
||||
}))
|
||||
vi.mock('@/lib/config-service', () => configServiceMock)
|
||||
vi.mock('@/lib/task/has-output', () => hasOutputMock)
|
||||
vi.mock('@/lib/billing', () => ({
|
||||
buildDefaultTaskBillingInfo: vi.fn(() => ({ mode: 'default' })),
|
||||
}))
|
||||
vi.mock('@/lib/providers/bailian/voice-design', () => ({
|
||||
validateVoicePrompt: vi.fn(() => ({ valid: true })),
|
||||
validatePreviewText: vi.fn(() => ({ valid: true })),
|
||||
}))
|
||||
vi.mock('@/lib/media/outbound-image', () => ({
|
||||
sanitizeImageInputsForTaskPayload: vi.fn((inputs: unknown[]) => ({
|
||||
normalized: inputs
|
||||
.filter((item): item is string => typeof item === 'string')
|
||||
.map((item) => item.trim())
|
||||
.filter((item) => item.length > 0),
|
||||
issues: [] as Array<{ reason: string }>,
|
||||
})),
|
||||
}))
|
||||
vi.mock('@/lib/model-capabilities/lookup', () => ({
|
||||
resolveBuiltinCapabilitiesByModelKey: vi.fn(() => ({ video: { firstlastframe: true } })),
|
||||
}))
|
||||
vi.mock('@/lib/model-pricing/lookup', () => ({
|
||||
resolveBuiltinPricing: vi.fn(() => ({ status: 'ok' })),
|
||||
}))
|
||||
vi.mock('@/lib/api-config', () => ({
|
||||
resolveModelSelection: vi.fn(async () => ({
|
||||
model: 'img::storyboard',
|
||||
})),
|
||||
resolveModelSelectionOrSingle: vi.fn(async (_userId: string, model: string | null | undefined) => {
|
||||
const modelKey = typeof model === 'string' && model.trim().length > 0
|
||||
? model.trim()
|
||||
: 'fal::audio-model'
|
||||
const separator = modelKey.indexOf('::')
|
||||
const provider = separator === -1 ? modelKey : modelKey.slice(0, separator)
|
||||
const modelId = separator === -1 ? modelKey : modelKey.slice(separator + 2)
|
||||
return {
|
||||
provider,
|
||||
modelId,
|
||||
modelKey,
|
||||
mediaType: 'audio',
|
||||
}
|
||||
}),
|
||||
getProviderKey: vi.fn((providerId: string) => {
|
||||
const marker = providerId.indexOf(':')
|
||||
return marker === -1 ? providerId : providerId.slice(0, marker)
|
||||
}),
|
||||
}))
|
||||
vi.mock('@/lib/prisma', () => ({
|
||||
prisma: prismaMock,
|
||||
}))
|
||||
|
||||
function toApiPath(routeFile: string): string {
|
||||
return routeFile
|
||||
.replace(/^src\/app/, '')
|
||||
.replace(/\/route\.ts$/, '')
|
||||
.replace('[projectId]', 'project-1')
|
||||
}
|
||||
|
||||
function toModuleImportPath(routeFile: string): string {
|
||||
return `@/${routeFile.replace(/^src\//, '').replace(/\.ts$/, '')}`
|
||||
}
|
||||
|
||||
const DIRECT_CASES: ReadonlyArray<DirectRouteCase> = [
|
||||
{
|
||||
routeFile: 'src/app/api/asset-hub/generate-image/route.ts',
|
||||
body: { type: 'character', id: 'global-character-1', appearanceIndex: 0, artStyle: 'realistic' },
|
||||
expectedTaskType: TASK_TYPE.ASSET_HUB_IMAGE,
|
||||
expectedTargetType: 'GlobalCharacter',
|
||||
expectedProjectId: 'global-asset-hub',
|
||||
},
|
||||
{
|
||||
routeFile: 'src/app/api/asset-hub/modify-image/route.ts',
|
||||
body: {
|
||||
type: 'character',
|
||||
id: 'global-character-1',
|
||||
modifyPrompt: 'sharpen details',
|
||||
appearanceIndex: 0,
|
||||
imageIndex: 0,
|
||||
extraImageUrls: ['https://example.com/ref-a.png'],
|
||||
},
|
||||
expectedTaskType: TASK_TYPE.ASSET_HUB_MODIFY,
|
||||
expectedTargetType: 'GlobalCharacterAppearance',
|
||||
expectedProjectId: 'global-asset-hub',
|
||||
},
|
||||
{
|
||||
routeFile: 'src/app/api/asset-hub/voice-design/route.ts',
|
||||
body: { voicePrompt: 'female calm narrator', previewText: '你好世界' },
|
||||
expectedTaskType: TASK_TYPE.ASSET_HUB_VOICE_DESIGN,
|
||||
expectedTargetType: 'GlobalAssetHubVoiceDesign',
|
||||
expectedProjectId: 'global-asset-hub',
|
||||
},
|
||||
{
|
||||
routeFile: 'src/app/api/novel-promotion/[projectId]/generate-image/route.ts',
|
||||
body: { type: 'character', id: 'character-1', appearanceId: 'appearance-1' },
|
||||
params: { projectId: 'project-1' },
|
||||
expectedTaskType: TASK_TYPE.IMAGE_CHARACTER,
|
||||
expectedTargetType: 'CharacterAppearance',
|
||||
expectedProjectId: 'project-1',
|
||||
},
|
||||
{
|
||||
routeFile: 'src/app/api/novel-promotion/[projectId]/generate-video/route.ts',
|
||||
body: { videoModel: 'fal::video-model', storyboardId: 'storyboard-1', panelIndex: 0 },
|
||||
params: { projectId: 'project-1' },
|
||||
expectedTaskType: TASK_TYPE.VIDEO_PANEL,
|
||||
expectedTargetType: 'NovelPromotionPanel',
|
||||
expectedProjectId: 'project-1',
|
||||
},
|
||||
{
|
||||
routeFile: 'src/app/api/novel-promotion/[projectId]/insert-panel/route.ts',
|
||||
body: { storyboardId: 'storyboard-1', insertAfterPanelId: 'panel-ins' },
|
||||
params: { projectId: 'project-1' },
|
||||
expectedTaskType: TASK_TYPE.INSERT_PANEL,
|
||||
expectedTargetType: 'NovelPromotionStoryboard',
|
||||
expectedProjectId: 'project-1',
|
||||
},
|
||||
{
|
||||
routeFile: 'src/app/api/novel-promotion/[projectId]/lip-sync/route.ts',
|
||||
body: {
|
||||
storyboardId: 'storyboard-1',
|
||||
panelIndex: 0,
|
||||
voiceLineId: 'line-1',
|
||||
lipSyncModel: 'fal::lip-model',
|
||||
},
|
||||
params: { projectId: 'project-1' },
|
||||
expectedTaskType: TASK_TYPE.LIP_SYNC,
|
||||
expectedTargetType: 'NovelPromotionPanel',
|
||||
expectedProjectId: 'project-1',
|
||||
},
|
||||
{
|
||||
routeFile: 'src/app/api/novel-promotion/[projectId]/modify-asset-image/route.ts',
|
||||
body: {
|
||||
type: 'character',
|
||||
characterId: 'character-1',
|
||||
appearanceId: 'appearance-1',
|
||||
modifyPrompt: 'enhance texture',
|
||||
extraImageUrls: ['https://example.com/ref-b.png'],
|
||||
},
|
||||
params: { projectId: 'project-1' },
|
||||
expectedTaskType: TASK_TYPE.MODIFY_ASSET_IMAGE,
|
||||
expectedTargetType: 'CharacterAppearance',
|
||||
expectedProjectId: 'project-1',
|
||||
},
|
||||
{
|
||||
routeFile: 'src/app/api/novel-promotion/[projectId]/modify-storyboard-image/route.ts',
|
||||
body: {
|
||||
storyboardId: 'storyboard-1',
|
||||
panelIndex: 0,
|
||||
modifyPrompt: 'increase contrast',
|
||||
extraImageUrls: ['https://example.com/ref-c.png'],
|
||||
selectedAssets: [{ imageUrl: 'https://example.com/ref-d.png' }],
|
||||
},
|
||||
params: { projectId: 'project-1' },
|
||||
expectedTaskType: TASK_TYPE.MODIFY_ASSET_IMAGE,
|
||||
expectedTargetType: 'NovelPromotionPanel',
|
||||
expectedProjectId: 'project-1',
|
||||
},
|
||||
{
|
||||
routeFile: 'src/app/api/novel-promotion/[projectId]/panel-variant/route.ts',
|
||||
body: {
|
||||
storyboardId: 'storyboard-1',
|
||||
insertAfterPanelId: 'panel-ins',
|
||||
sourcePanelId: 'panel-src',
|
||||
variant: { video_prompt: 'new prompt', description: 'variant desc' },
|
||||
},
|
||||
params: { projectId: 'project-1' },
|
||||
expectedTaskType: TASK_TYPE.PANEL_VARIANT,
|
||||
expectedTargetType: 'NovelPromotionPanel',
|
||||
expectedProjectId: 'project-1',
|
||||
},
|
||||
{
|
||||
routeFile: 'src/app/api/novel-promotion/[projectId]/regenerate-group/route.ts',
|
||||
body: { type: 'character', id: 'character-1', appearanceId: 'appearance-1' },
|
||||
params: { projectId: 'project-1' },
|
||||
expectedTaskType: TASK_TYPE.REGENERATE_GROUP,
|
||||
expectedTargetType: 'CharacterAppearance',
|
||||
expectedProjectId: 'project-1',
|
||||
},
|
||||
{
|
||||
routeFile: 'src/app/api/novel-promotion/[projectId]/regenerate-panel-image/route.ts',
|
||||
body: { panelId: 'panel-1', count: 1 },
|
||||
params: { projectId: 'project-1' },
|
||||
expectedTaskType: TASK_TYPE.IMAGE_PANEL,
|
||||
expectedTargetType: 'NovelPromotionPanel',
|
||||
expectedProjectId: 'project-1',
|
||||
},
|
||||
{
|
||||
routeFile: 'src/app/api/novel-promotion/[projectId]/regenerate-single-image/route.ts',
|
||||
body: { type: 'character', id: 'character-1', appearanceId: 'appearance-1', imageIndex: 0 },
|
||||
params: { projectId: 'project-1' },
|
||||
expectedTaskType: TASK_TYPE.IMAGE_CHARACTER,
|
||||
expectedTargetType: 'CharacterAppearance',
|
||||
expectedProjectId: 'project-1',
|
||||
},
|
||||
{
|
||||
routeFile: 'src/app/api/novel-promotion/[projectId]/regenerate-storyboard-text/route.ts',
|
||||
body: { storyboardId: 'storyboard-1' },
|
||||
params: { projectId: 'project-1' },
|
||||
expectedTaskType: TASK_TYPE.REGENERATE_STORYBOARD_TEXT,
|
||||
expectedTargetType: 'NovelPromotionStoryboard',
|
||||
expectedProjectId: 'project-1',
|
||||
},
|
||||
{
|
||||
routeFile: 'src/app/api/novel-promotion/[projectId]/voice-design/route.ts',
|
||||
body: { voicePrompt: 'warm female voice', previewText: 'This is preview text' },
|
||||
params: { projectId: 'project-1' },
|
||||
expectedTaskType: TASK_TYPE.VOICE_DESIGN,
|
||||
expectedTargetType: 'NovelPromotionProject',
|
||||
expectedProjectId: 'project-1',
|
||||
},
|
||||
{
|
||||
routeFile: 'src/app/api/novel-promotion/[projectId]/voice-generate/route.ts',
|
||||
body: { episodeId: 'episode-1', lineId: 'line-1', audioModel: 'fal::audio-model' },
|
||||
params: { projectId: 'project-1' },
|
||||
expectedTaskType: TASK_TYPE.VOICE_LINE,
|
||||
expectedTargetType: 'NovelPromotionVoiceLine',
|
||||
expectedProjectId: 'project-1',
|
||||
},
|
||||
]
|
||||
|
||||
async function invokePostRoute(routeCase: DirectRouteCase): Promise<Response> {
|
||||
const modulePath = toModuleImportPath(routeCase.routeFile)
|
||||
const mod = await import(modulePath)
|
||||
const post = mod.POST as (request: Request, context?: RouteContext) => Promise<Response>
|
||||
const req = buildMockRequest({
|
||||
path: toApiPath(routeCase.routeFile),
|
||||
method: 'POST',
|
||||
body: routeCase.body,
|
||||
})
|
||||
return await post(req, { params: Promise.resolve(routeCase.params || {}) })
|
||||
}
|
||||
|
||||
describe('api contract - direct submit routes (behavior)', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
authState.authenticated = true
|
||||
authState.projectMode = 'novel-promotion'
|
||||
let seq = 0
|
||||
submitTaskMock.mockImplementation(async () => ({
|
||||
taskId: `task-${++seq}`,
|
||||
async: true,
|
||||
}))
|
||||
})
|
||||
|
||||
it('keeps expected coverage size', () => {
|
||||
expect(DIRECT_CASES.length).toBe(16)
|
||||
})
|
||||
|
||||
for (const routeCase of DIRECT_CASES) {
|
||||
it(`${routeCase.routeFile} -> returns 401 when unauthenticated`, async () => {
|
||||
authState.authenticated = false
|
||||
const res = await invokePostRoute(routeCase)
|
||||
expect(res.status).toBe(401)
|
||||
expect(submitTaskMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it(`${routeCase.routeFile} -> submits task with expected contract when authenticated`, async () => {
|
||||
const res = await invokePostRoute(routeCase)
|
||||
expect(res.status).toBe(200)
|
||||
expect(submitTaskMock).toHaveBeenCalledWith(expect.objectContaining({
|
||||
type: routeCase.expectedTaskType,
|
||||
targetType: routeCase.expectedTargetType,
|
||||
projectId: routeCase.expectedProjectId,
|
||||
userId: 'user-1',
|
||||
}))
|
||||
|
||||
const submitArg = submitTaskMock.mock.calls.at(-1)?.[0] as Record<string, unknown> | undefined
|
||||
expect(submitArg?.type).toBe(routeCase.expectedTaskType)
|
||||
expect(submitArg?.targetType).toBe(routeCase.expectedTargetType)
|
||||
expect(submitArg?.projectId).toBe(routeCase.expectedProjectId)
|
||||
expect(submitArg?.userId).toBe('user-1')
|
||||
|
||||
const json = await res.json() as Record<string, unknown>
|
||||
const isVoiceGenerateRoute = routeCase.routeFile.endsWith('/voice-generate/route.ts')
|
||||
if (isVoiceGenerateRoute) {
|
||||
expect(json.success).toBe(true)
|
||||
expect(json.async).toBe(true)
|
||||
expect(typeof json.taskId).toBe('string')
|
||||
} else {
|
||||
expect(json.async).toBe(true)
|
||||
expect(typeof json.taskId).toBe('string')
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
371
tests/integration/api/contract/llm-observe-routes.test.ts
Normal file
371
tests/integration/api/contract/llm-observe-routes.test.ts
Normal file
@@ -0,0 +1,371 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { TASK_TYPE, type TaskType } from '@/lib/task/types'
|
||||
import { buildMockRequest } from '../../../helpers/request'
|
||||
|
||||
type AuthState = {
|
||||
authenticated: boolean
|
||||
projectMode: 'novel-promotion' | 'other'
|
||||
}
|
||||
|
||||
type LLMRouteCase = {
|
||||
routeFile: string
|
||||
body: Record<string, unknown>
|
||||
params?: Record<string, string>
|
||||
expectedTaskType: TaskType
|
||||
expectedTargetType: string
|
||||
expectedProjectId: string
|
||||
}
|
||||
|
||||
type RouteContext = {
|
||||
params: Promise<Record<string, string>>
|
||||
}
|
||||
|
||||
const authState = vi.hoisted<AuthState>(() => ({
|
||||
authenticated: true,
|
||||
projectMode: 'novel-promotion',
|
||||
}))
|
||||
|
||||
const maybeSubmitLLMTaskMock = vi.hoisted(() =>
|
||||
vi.fn<typeof import('@/lib/llm-observe/route-task').maybeSubmitLLMTask>(async () => NextResponse.json({
|
||||
success: true,
|
||||
async: true,
|
||||
taskId: 'task-1',
|
||||
runId: null,
|
||||
status: 'queued',
|
||||
deduped: false,
|
||||
})),
|
||||
)
|
||||
|
||||
const configServiceMock = vi.hoisted(() => ({
|
||||
getUserModelConfig: vi.fn(async () => ({
|
||||
analysisModel: 'llm::analysis',
|
||||
})),
|
||||
getProjectModelConfig: vi.fn(async () => ({
|
||||
analysisModel: 'llm::analysis',
|
||||
})),
|
||||
}))
|
||||
|
||||
const prismaMock = vi.hoisted(() => ({
|
||||
globalCharacter: {
|
||||
findUnique: vi.fn(async () => ({
|
||||
id: 'global-character-1',
|
||||
userId: 'user-1',
|
||||
})),
|
||||
},
|
||||
globalLocation: {
|
||||
findUnique: vi.fn(async () => ({
|
||||
id: 'global-location-1',
|
||||
userId: 'user-1',
|
||||
})),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/api-auth', () => {
|
||||
const unauthorized = () => new Response(
|
||||
JSON.stringify({ error: { code: 'UNAUTHORIZED' } }),
|
||||
{ status: 401, headers: { 'content-type': 'application/json' } },
|
||||
)
|
||||
|
||||
return {
|
||||
isErrorResponse: (value: unknown) => value instanceof Response,
|
||||
requireUserAuth: async () => {
|
||||
if (!authState.authenticated) return unauthorized()
|
||||
return { session: { user: { id: 'user-1' } } }
|
||||
},
|
||||
requireProjectAuth: async (projectId: string) => {
|
||||
if (!authState.authenticated) return unauthorized()
|
||||
return {
|
||||
session: { user: { id: 'user-1' } },
|
||||
project: { id: projectId, userId: 'user-1', mode: authState.projectMode },
|
||||
}
|
||||
},
|
||||
requireProjectAuthLight: async (projectId: string) => {
|
||||
if (!authState.authenticated) return unauthorized()
|
||||
return {
|
||||
session: { user: { id: 'user-1' } },
|
||||
project: { id: projectId, userId: 'user-1', mode: authState.projectMode },
|
||||
}
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@/lib/llm-observe/route-task', () => ({
|
||||
maybeSubmitLLMTask: maybeSubmitLLMTaskMock,
|
||||
}))
|
||||
vi.mock('@/lib/config-service', () => configServiceMock)
|
||||
vi.mock('@/lib/prisma', () => ({
|
||||
prisma: prismaMock,
|
||||
}))
|
||||
|
||||
function toApiPath(routeFile: string): string {
|
||||
return routeFile
|
||||
.replace(/^src\/app/, '')
|
||||
.replace(/\/route\.ts$/, '')
|
||||
.replace('[projectId]', 'project-1')
|
||||
}
|
||||
|
||||
function toModuleImportPath(routeFile: string): string {
|
||||
return `@/${routeFile.replace(/^src\//, '').replace(/\.ts$/, '')}`
|
||||
}
|
||||
|
||||
const ROUTE_CASES: ReadonlyArray<LLMRouteCase> = [
|
||||
{
|
||||
routeFile: 'src/app/api/asset-hub/ai-design-character/route.ts',
|
||||
body: { userInstruction: 'design a heroic character' },
|
||||
expectedTaskType: TASK_TYPE.ASSET_HUB_AI_DESIGN_CHARACTER,
|
||||
expectedTargetType: 'GlobalAssetHubCharacterDesign',
|
||||
expectedProjectId: 'global-asset-hub',
|
||||
},
|
||||
{
|
||||
routeFile: 'src/app/api/asset-hub/ai-design-location/route.ts',
|
||||
body: { userInstruction: 'design a noir city location' },
|
||||
expectedTaskType: TASK_TYPE.ASSET_HUB_AI_DESIGN_LOCATION,
|
||||
expectedTargetType: 'GlobalAssetHubLocationDesign',
|
||||
expectedProjectId: 'global-asset-hub',
|
||||
},
|
||||
{
|
||||
routeFile: 'src/app/api/asset-hub/ai-modify-character/route.ts',
|
||||
body: {
|
||||
characterId: 'global-character-1',
|
||||
appearanceIndex: 0,
|
||||
currentDescription: 'old desc',
|
||||
modifyInstruction: 'make the outfit darker',
|
||||
},
|
||||
expectedTaskType: TASK_TYPE.ASSET_HUB_AI_MODIFY_CHARACTER,
|
||||
expectedTargetType: 'GlobalCharacter',
|
||||
expectedProjectId: 'global-asset-hub',
|
||||
},
|
||||
{
|
||||
routeFile: 'src/app/api/asset-hub/ai-modify-location/route.ts',
|
||||
body: {
|
||||
locationId: 'global-location-1',
|
||||
imageIndex: 0,
|
||||
currentDescription: 'old location desc',
|
||||
modifyInstruction: 'add more fog',
|
||||
},
|
||||
expectedTaskType: TASK_TYPE.ASSET_HUB_AI_MODIFY_LOCATION,
|
||||
expectedTargetType: 'GlobalLocation',
|
||||
expectedProjectId: 'global-asset-hub',
|
||||
},
|
||||
{
|
||||
routeFile: 'src/app/api/asset-hub/reference-to-character/route.ts',
|
||||
body: { referenceImageUrl: 'https://example.com/ref.png' },
|
||||
expectedTaskType: TASK_TYPE.ASSET_HUB_REFERENCE_TO_CHARACTER,
|
||||
expectedTargetType: 'GlobalCharacter',
|
||||
expectedProjectId: 'global-asset-hub',
|
||||
},
|
||||
{
|
||||
routeFile: 'src/app/api/novel-promotion/[projectId]/ai-create-character/route.ts',
|
||||
body: { userInstruction: 'create a rebel hero' },
|
||||
params: { projectId: 'project-1' },
|
||||
expectedTaskType: TASK_TYPE.AI_CREATE_CHARACTER,
|
||||
expectedTargetType: 'NovelPromotionCharacterDesign',
|
||||
expectedProjectId: 'project-1',
|
||||
},
|
||||
{
|
||||
routeFile: 'src/app/api/novel-promotion/[projectId]/ai-create-location/route.ts',
|
||||
body: { userInstruction: 'create a mountain temple' },
|
||||
params: { projectId: 'project-1' },
|
||||
expectedTaskType: TASK_TYPE.AI_CREATE_LOCATION,
|
||||
expectedTargetType: 'NovelPromotionLocationDesign',
|
||||
expectedProjectId: 'project-1',
|
||||
},
|
||||
{
|
||||
routeFile: 'src/app/api/novel-promotion/[projectId]/ai-modify-appearance/route.ts',
|
||||
body: {
|
||||
characterId: 'character-1',
|
||||
appearanceId: 'appearance-1',
|
||||
currentDescription: 'old appearance',
|
||||
modifyInstruction: 'add armor',
|
||||
},
|
||||
params: { projectId: 'project-1' },
|
||||
expectedTaskType: TASK_TYPE.AI_MODIFY_APPEARANCE,
|
||||
expectedTargetType: 'CharacterAppearance',
|
||||
expectedProjectId: 'project-1',
|
||||
},
|
||||
{
|
||||
routeFile: 'src/app/api/novel-promotion/[projectId]/ai-modify-location/route.ts',
|
||||
body: {
|
||||
locationId: 'location-1',
|
||||
currentDescription: 'old location',
|
||||
modifyInstruction: 'add rain',
|
||||
},
|
||||
params: { projectId: 'project-1' },
|
||||
expectedTaskType: TASK_TYPE.AI_MODIFY_LOCATION,
|
||||
expectedTargetType: 'NovelPromotionLocation',
|
||||
expectedProjectId: 'project-1',
|
||||
},
|
||||
{
|
||||
routeFile: 'src/app/api/novel-promotion/[projectId]/ai-modify-shot-prompt/route.ts',
|
||||
body: {
|
||||
panelId: 'panel-1',
|
||||
currentPrompt: 'old prompt',
|
||||
modifyInstruction: 'more dramatic angle',
|
||||
},
|
||||
params: { projectId: 'project-1' },
|
||||
expectedTaskType: TASK_TYPE.AI_MODIFY_SHOT_PROMPT,
|
||||
expectedTargetType: 'NovelPromotionPanel',
|
||||
expectedProjectId: 'project-1',
|
||||
},
|
||||
{
|
||||
routeFile: 'src/app/api/novel-promotion/[projectId]/analyze-global/route.ts',
|
||||
body: {},
|
||||
params: { projectId: 'project-1' },
|
||||
expectedTaskType: TASK_TYPE.ANALYZE_GLOBAL,
|
||||
expectedTargetType: 'NovelPromotionProject',
|
||||
expectedProjectId: 'project-1',
|
||||
},
|
||||
{
|
||||
routeFile: 'src/app/api/novel-promotion/[projectId]/analyze-shot-variants/route.ts',
|
||||
body: { panelId: 'panel-1' },
|
||||
params: { projectId: 'project-1' },
|
||||
expectedTaskType: TASK_TYPE.ANALYZE_SHOT_VARIANTS,
|
||||
expectedTargetType: 'NovelPromotionPanel',
|
||||
expectedProjectId: 'project-1',
|
||||
},
|
||||
{
|
||||
routeFile: 'src/app/api/novel-promotion/[projectId]/analyze/route.ts',
|
||||
body: { episodeId: 'episode-1', content: 'Analyze this chapter' },
|
||||
params: { projectId: 'project-1' },
|
||||
expectedTaskType: TASK_TYPE.ANALYZE_NOVEL,
|
||||
expectedTargetType: 'NovelPromotionProject',
|
||||
expectedProjectId: 'project-1',
|
||||
},
|
||||
{
|
||||
routeFile: 'src/app/api/novel-promotion/[projectId]/character-profile/batch-confirm/route.ts',
|
||||
body: { items: ['character-1', 'character-2'] },
|
||||
params: { projectId: 'project-1' },
|
||||
expectedTaskType: TASK_TYPE.CHARACTER_PROFILE_BATCH_CONFIRM,
|
||||
expectedTargetType: 'NovelPromotionProject',
|
||||
expectedProjectId: 'project-1',
|
||||
},
|
||||
{
|
||||
routeFile: 'src/app/api/novel-promotion/[projectId]/character-profile/confirm/route.ts',
|
||||
body: { characterId: 'character-1' },
|
||||
params: { projectId: 'project-1' },
|
||||
expectedTaskType: TASK_TYPE.CHARACTER_PROFILE_CONFIRM,
|
||||
expectedTargetType: 'NovelPromotionCharacter',
|
||||
expectedProjectId: 'project-1',
|
||||
},
|
||||
{
|
||||
routeFile: 'src/app/api/novel-promotion/[projectId]/clips/route.ts',
|
||||
body: { episodeId: 'episode-1' },
|
||||
params: { projectId: 'project-1' },
|
||||
expectedTaskType: TASK_TYPE.CLIPS_BUILD,
|
||||
expectedTargetType: 'NovelPromotionEpisode',
|
||||
expectedProjectId: 'project-1',
|
||||
},
|
||||
{
|
||||
routeFile: 'src/app/api/novel-promotion/[projectId]/episodes/split/route.ts',
|
||||
body: { content: 'x'.repeat(120) },
|
||||
params: { projectId: 'project-1' },
|
||||
expectedTaskType: TASK_TYPE.EPISODE_SPLIT_LLM,
|
||||
expectedTargetType: 'NovelPromotionProject',
|
||||
expectedProjectId: 'project-1',
|
||||
},
|
||||
{
|
||||
routeFile: 'src/app/api/novel-promotion/[projectId]/reference-to-character/route.ts',
|
||||
body: { referenceImageUrl: 'https://example.com/ref.png' },
|
||||
params: { projectId: 'project-1' },
|
||||
expectedTaskType: TASK_TYPE.REFERENCE_TO_CHARACTER,
|
||||
expectedTargetType: 'NovelPromotionProject',
|
||||
expectedProjectId: 'project-1',
|
||||
},
|
||||
{
|
||||
routeFile: 'src/app/api/novel-promotion/[projectId]/screenplay-conversion/route.ts',
|
||||
body: { episodeId: 'episode-1' },
|
||||
params: { projectId: 'project-1' },
|
||||
expectedTaskType: TASK_TYPE.SCREENPLAY_CONVERT,
|
||||
expectedTargetType: 'NovelPromotionEpisode',
|
||||
expectedProjectId: 'project-1',
|
||||
},
|
||||
{
|
||||
routeFile: 'src/app/api/novel-promotion/[projectId]/script-to-storyboard-stream/route.ts',
|
||||
body: { episodeId: 'episode-1' },
|
||||
params: { projectId: 'project-1' },
|
||||
expectedTaskType: TASK_TYPE.SCRIPT_TO_STORYBOARD_RUN,
|
||||
expectedTargetType: 'NovelPromotionEpisode',
|
||||
expectedProjectId: 'project-1',
|
||||
},
|
||||
{
|
||||
routeFile: 'src/app/api/novel-promotion/[projectId]/story-to-script-stream/route.ts',
|
||||
body: { episodeId: 'episode-1', content: 'story text' },
|
||||
params: { projectId: 'project-1' },
|
||||
expectedTaskType: TASK_TYPE.STORY_TO_SCRIPT_RUN,
|
||||
expectedTargetType: 'NovelPromotionEpisode',
|
||||
expectedProjectId: 'project-1',
|
||||
},
|
||||
{
|
||||
routeFile: 'src/app/api/novel-promotion/[projectId]/voice-analyze/route.ts',
|
||||
body: { episodeId: 'episode-1' },
|
||||
params: { projectId: 'project-1' },
|
||||
expectedTaskType: TASK_TYPE.VOICE_ANALYZE,
|
||||
expectedTargetType: 'NovelPromotionEpisode',
|
||||
expectedProjectId: 'project-1',
|
||||
},
|
||||
]
|
||||
|
||||
async function invokePostRoute(routeCase: LLMRouteCase): Promise<Response> {
|
||||
const modulePath = toModuleImportPath(routeCase.routeFile)
|
||||
const mod = await import(modulePath)
|
||||
const post = mod.POST as (request: Request, context?: RouteContext) => Promise<Response>
|
||||
const req = buildMockRequest({
|
||||
path: toApiPath(routeCase.routeFile),
|
||||
method: 'POST',
|
||||
body: routeCase.body,
|
||||
})
|
||||
return await post(req, { params: Promise.resolve(routeCase.params || {}) })
|
||||
}
|
||||
|
||||
describe('api contract - llm observe routes (behavior)', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
authState.authenticated = true
|
||||
authState.projectMode = 'novel-promotion'
|
||||
maybeSubmitLLMTaskMock.mockResolvedValue(
|
||||
NextResponse.json({
|
||||
success: true,
|
||||
async: true,
|
||||
taskId: 'task-1',
|
||||
runId: null,
|
||||
status: 'queued',
|
||||
deduped: false,
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('keeps expected coverage size', () => {
|
||||
expect(ROUTE_CASES.length).toBe(22)
|
||||
})
|
||||
|
||||
for (const routeCase of ROUTE_CASES) {
|
||||
it(`${routeCase.routeFile} -> returns 401 when unauthenticated`, async () => {
|
||||
authState.authenticated = false
|
||||
const res = await invokePostRoute(routeCase)
|
||||
expect(res.status).toBe(401)
|
||||
expect(maybeSubmitLLMTaskMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it(`${routeCase.routeFile} -> submits llm task with expected contract when authenticated`, async () => {
|
||||
const res = await invokePostRoute(routeCase)
|
||||
expect(res.status).toBe(200)
|
||||
expect(maybeSubmitLLMTaskMock).toHaveBeenCalledWith(expect.objectContaining({
|
||||
type: routeCase.expectedTaskType,
|
||||
targetType: routeCase.expectedTargetType,
|
||||
projectId: routeCase.expectedProjectId,
|
||||
userId: 'user-1',
|
||||
}))
|
||||
|
||||
const callArg = maybeSubmitLLMTaskMock.mock.calls.at(-1)?.[0] as Record<string, unknown> | undefined
|
||||
expect(callArg?.type).toBe(routeCase.expectedTaskType)
|
||||
expect(callArg?.targetType).toBe(routeCase.expectedTargetType)
|
||||
expect(callArg?.projectId).toBe(routeCase.expectedProjectId)
|
||||
expect(callArg?.userId).toBe('user-1')
|
||||
|
||||
const json = await res.json() as Record<string, unknown>
|
||||
expect(json.async).toBe(true)
|
||||
expect(typeof json.taskId).toBe('string')
|
||||
})
|
||||
}
|
||||
})
|
||||
134
tests/integration/api/contract/run-step-retry.route.test.ts
Normal file
134
tests/integration/api/contract/run-step-retry.route.test.ts
Normal file
@@ -0,0 +1,134 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { buildMockRequest } from '../../../helpers/request'
|
||||
|
||||
type RouteContext = {
|
||||
params: Promise<{ runId: string; stepKey: string }>
|
||||
}
|
||||
|
||||
const authState = vi.hoisted(() => ({ authenticated: true }))
|
||||
const getRunByIdMock = vi.hoisted(() => vi.fn())
|
||||
const retryFailedStepMock = vi.hoisted(() => vi.fn())
|
||||
const submitTaskMock = vi.hoisted(() => vi.fn())
|
||||
const resolveRequiredTaskLocaleMock = vi.hoisted(() => vi.fn(() => 'zh'))
|
||||
|
||||
vi.mock('@/lib/api-auth', () => {
|
||||
const unauthorized = () => new Response(
|
||||
JSON.stringify({ error: { code: 'UNAUTHORIZED' } }),
|
||||
{ status: 401, headers: { 'content-type': 'application/json' } },
|
||||
)
|
||||
|
||||
return {
|
||||
isErrorResponse: (value: unknown) => value instanceof Response,
|
||||
requireUserAuth: async () => {
|
||||
if (!authState.authenticated) return unauthorized()
|
||||
return { session: { user: { id: 'user-1' } } }
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@/lib/run-runtime/service', () => ({
|
||||
getRunById: getRunByIdMock,
|
||||
retryFailedStep: retryFailedStepMock,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/task/submitter', () => ({
|
||||
submitTask: submitTaskMock,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/task/resolve-locale', () => ({
|
||||
resolveRequiredTaskLocale: resolveRequiredTaskLocaleMock,
|
||||
}))
|
||||
|
||||
describe('api contract - run step retry route', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
authState.authenticated = true
|
||||
|
||||
getRunByIdMock.mockResolvedValue({
|
||||
id: 'run-1',
|
||||
userId: 'user-1',
|
||||
projectId: 'project-1',
|
||||
episodeId: 'episode-1',
|
||||
workflowType: 'story_to_script_run',
|
||||
taskType: 'story_to_script_run',
|
||||
targetType: 'NovelPromotionEpisode',
|
||||
targetId: 'episode-1',
|
||||
input: {
|
||||
episodeId: 'episode-1',
|
||||
content: 'test content',
|
||||
meta: { locale: 'zh' },
|
||||
},
|
||||
})
|
||||
retryFailedStepMock.mockResolvedValue({
|
||||
run: { id: 'run-1' },
|
||||
step: { stepKey: 'screenplay_clip_2' },
|
||||
retryAttempt: 2,
|
||||
})
|
||||
submitTaskMock.mockResolvedValue({
|
||||
success: true,
|
||||
async: true,
|
||||
taskId: 'task-retry-1',
|
||||
runId: 'run-1',
|
||||
status: 'queued',
|
||||
deduped: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects retry when step is not failed', async () => {
|
||||
retryFailedStepMock.mockRejectedValue(new Error('RUN_STEP_NOT_FAILED'))
|
||||
const route = await import('@/app/api/runs/[runId]/steps/[stepKey]/retry/route')
|
||||
|
||||
const req = buildMockRequest({
|
||||
path: '/api/runs/run-1/steps/screenplay_clip_2/retry',
|
||||
method: 'POST',
|
||||
body: { modelOverride: 'openai/gpt-5' },
|
||||
})
|
||||
const res = await route.POST(req, {
|
||||
params: Promise.resolve({ runId: 'run-1', stepKey: 'screenplay_clip_2' }),
|
||||
} as RouteContext)
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
expect(submitTaskMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('submits retry task bound to existing run id', async () => {
|
||||
const route = await import('@/app/api/runs/[runId]/steps/[stepKey]/retry/route')
|
||||
|
||||
const req = buildMockRequest({
|
||||
path: '/api/runs/run-1/steps/screenplay_clip_2/retry',
|
||||
method: 'POST',
|
||||
body: {
|
||||
modelOverride: 'openai/gpt-5',
|
||||
reason: 'manual retry',
|
||||
},
|
||||
})
|
||||
const res = await route.POST(req, {
|
||||
params: Promise.resolve({ runId: 'run-1', stepKey: 'screenplay_clip_2' }),
|
||||
} as RouteContext)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const payload = await res.json() as {
|
||||
success: boolean
|
||||
runId: string
|
||||
stepKey: string
|
||||
retryAttempt: number
|
||||
taskId: string
|
||||
}
|
||||
expect(payload.success).toBe(true)
|
||||
expect(payload.runId).toBe('run-1')
|
||||
expect(payload.stepKey).toBe('screenplay_clip_2')
|
||||
expect(payload.retryAttempt).toBe(2)
|
||||
expect(payload.taskId).toBe('task-retry-1')
|
||||
|
||||
expect(submitTaskMock).toHaveBeenCalledWith(expect.objectContaining({
|
||||
projectId: 'project-1',
|
||||
type: 'story_to_script_run',
|
||||
payload: expect.objectContaining({
|
||||
runId: 'run-1',
|
||||
retryStepKey: 'screenplay_clip_2',
|
||||
retryStepAttempt: 2,
|
||||
model: 'openai/gpt-5',
|
||||
}),
|
||||
}))
|
||||
})
|
||||
})
|
||||
463
tests/integration/api/contract/task-infra-routes.test.ts
Normal file
463
tests/integration/api/contract/task-infra-routes.test.ts
Normal file
@@ -0,0 +1,463 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { TASK_STATUS } from '@/lib/task/types'
|
||||
import { buildMockRequest } from '../../../helpers/request'
|
||||
|
||||
type AuthState = {
|
||||
authenticated: boolean
|
||||
}
|
||||
|
||||
type RouteContext = {
|
||||
params: Promise<{ taskId: string }>
|
||||
}
|
||||
|
||||
type EmptyRouteContext = {
|
||||
params: Promise<Record<string, string>>
|
||||
}
|
||||
|
||||
type ReplayEvent = Awaited<ReturnType<typeof import('@/lib/task/publisher').listEventsAfter>>[number]
|
||||
type TaskLifecycleReplayEvent = Awaited<ReturnType<typeof import('@/lib/task/publisher').listTaskLifecycleEvents>>[number]
|
||||
|
||||
type TaskRecord = {
|
||||
id: string
|
||||
userId: string
|
||||
projectId: string
|
||||
type: string
|
||||
targetType: string
|
||||
targetId: string
|
||||
status: string
|
||||
errorCode: string | null
|
||||
errorMessage: string | null
|
||||
}
|
||||
|
||||
const authState = vi.hoisted<AuthState>(() => ({
|
||||
authenticated: true,
|
||||
}))
|
||||
|
||||
const queryTasksMock = vi.hoisted(() => vi.fn())
|
||||
const dismissFailedTasksMock = vi.hoisted(() => vi.fn())
|
||||
const getTaskByIdMock = vi.hoisted(() => vi.fn())
|
||||
const cancelTaskMock = vi.hoisted(() => vi.fn())
|
||||
const removeTaskJobMock = vi.hoisted(() => vi.fn(async () => true))
|
||||
const publishTaskEventMock = vi.hoisted(() => vi.fn(async () => undefined))
|
||||
const queryTaskTargetStatesMock = vi.hoisted(() => vi.fn())
|
||||
const withPrismaRetryMock = vi.hoisted(() => vi.fn(async <T>(fn: () => Promise<T>) => await fn()))
|
||||
const listEventsAfterMock = vi.hoisted(() =>
|
||||
vi.fn<typeof import('@/lib/task/publisher').listEventsAfter>(async () => []),
|
||||
)
|
||||
const listTaskLifecycleEventsMock = vi.hoisted(() =>
|
||||
vi.fn<typeof import('@/lib/task/publisher').listTaskLifecycleEvents>(async () => []),
|
||||
)
|
||||
const addChannelListenerMock = vi.hoisted(() =>
|
||||
vi.fn<(channel: string, listener: (message: string) => void) => Promise<() => Promise<void>>>(
|
||||
async () => async () => undefined,
|
||||
),
|
||||
)
|
||||
const subscriberState = vi.hoisted(() => ({
|
||||
listener: null as ((message: string) => void) | null,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/api-auth', () => {
|
||||
const unauthorized = () => new Response(
|
||||
JSON.stringify({ error: { code: 'UNAUTHORIZED' } }),
|
||||
{ status: 401, headers: { 'content-type': 'application/json' } },
|
||||
)
|
||||
|
||||
return {
|
||||
isErrorResponse: (value: unknown) => value instanceof Response,
|
||||
requireUserAuth: async () => {
|
||||
if (!authState.authenticated) return unauthorized()
|
||||
return { session: { user: { id: 'user-1' } } }
|
||||
},
|
||||
requireProjectAuthLight: async (projectId: string) => {
|
||||
if (!authState.authenticated) return unauthorized()
|
||||
return {
|
||||
session: { user: { id: 'user-1' } },
|
||||
project: { id: projectId, userId: 'user-1' },
|
||||
}
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@/lib/task/service', () => ({
|
||||
queryTasks: queryTasksMock,
|
||||
dismissFailedTasks: dismissFailedTasksMock,
|
||||
getTaskById: getTaskByIdMock,
|
||||
cancelTask: cancelTaskMock,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/task/queues', () => ({
|
||||
removeTaskJob: removeTaskJobMock,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/task/publisher', () => ({
|
||||
publishTaskEvent: publishTaskEventMock,
|
||||
getProjectChannel: vi.fn((projectId: string) => `project:${projectId}`),
|
||||
listEventsAfter: listEventsAfterMock,
|
||||
listTaskLifecycleEvents: listTaskLifecycleEventsMock,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/task/state-service', () => ({
|
||||
queryTaskTargetStates: queryTaskTargetStatesMock,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/prisma-retry', () => ({
|
||||
withPrismaRetry: withPrismaRetryMock,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/sse/shared-subscriber', () => ({
|
||||
getSharedSubscriber: vi.fn(() => ({
|
||||
addChannelListener: addChannelListenerMock,
|
||||
})),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/prisma', () => ({
|
||||
prisma: {
|
||||
task: {
|
||||
findMany: vi.fn(async () => []),
|
||||
},
|
||||
},
|
||||
}))
|
||||
|
||||
const baseTask: TaskRecord = {
|
||||
id: 'task-1',
|
||||
userId: 'user-1',
|
||||
projectId: 'project-1',
|
||||
type: 'IMAGE_CHARACTER',
|
||||
targetType: 'CharacterAppearance',
|
||||
targetId: 'appearance-1',
|
||||
status: TASK_STATUS.FAILED,
|
||||
errorCode: null,
|
||||
errorMessage: null,
|
||||
}
|
||||
|
||||
describe('api contract - task infra routes (behavior)', () => {
|
||||
const emptyRouteContext: EmptyRouteContext = { params: Promise.resolve({}) }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
authState.authenticated = true
|
||||
subscriberState.listener = null
|
||||
|
||||
queryTasksMock.mockResolvedValue([baseTask])
|
||||
dismissFailedTasksMock.mockResolvedValue(1)
|
||||
getTaskByIdMock.mockResolvedValue(baseTask)
|
||||
cancelTaskMock.mockResolvedValue({
|
||||
task: {
|
||||
...baseTask,
|
||||
status: TASK_STATUS.FAILED,
|
||||
errorCode: 'TASK_CANCELLED',
|
||||
errorMessage: 'Task cancelled by user',
|
||||
},
|
||||
cancelled: true,
|
||||
})
|
||||
queryTaskTargetStatesMock.mockResolvedValue([
|
||||
{
|
||||
targetType: 'CharacterAppearance',
|
||||
targetId: 'appearance-1',
|
||||
active: true,
|
||||
status: TASK_STATUS.PROCESSING,
|
||||
taskId: 'task-1',
|
||||
updatedAt: new Date().toISOString(),
|
||||
},
|
||||
])
|
||||
addChannelListenerMock.mockImplementation(async (_channel: string, listener: (message: string) => void) => {
|
||||
subscriberState.listener = listener
|
||||
return async () => undefined
|
||||
})
|
||||
listTaskLifecycleEventsMock.mockResolvedValue([])
|
||||
})
|
||||
|
||||
it('GET /api/tasks: unauthenticated -> 401; authenticated -> 200 with caller-owned tasks', async () => {
|
||||
const { GET } = await import('@/app/api/tasks/route')
|
||||
|
||||
authState.authenticated = false
|
||||
const unauthorizedReq = buildMockRequest({
|
||||
path: '/api/tasks',
|
||||
method: 'GET',
|
||||
query: { projectId: 'project-1', limit: 20 },
|
||||
})
|
||||
const unauthorizedRes = await GET(unauthorizedReq, emptyRouteContext)
|
||||
expect(unauthorizedRes.status).toBe(401)
|
||||
|
||||
authState.authenticated = true
|
||||
const req = buildMockRequest({
|
||||
path: '/api/tasks',
|
||||
method: 'GET',
|
||||
query: { projectId: 'project-1', limit: 20, targetId: 'appearance-1' },
|
||||
})
|
||||
const res = await GET(req, emptyRouteContext)
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
const payload = await res.json() as { tasks: TaskRecord[] }
|
||||
expect(payload.tasks).toHaveLength(1)
|
||||
expect(payload.tasks[0]?.id).toBe('task-1')
|
||||
expect(queryTasksMock).toHaveBeenCalledWith(expect.objectContaining({
|
||||
projectId: 'project-1',
|
||||
targetId: 'appearance-1',
|
||||
limit: 20,
|
||||
}))
|
||||
})
|
||||
|
||||
it('POST /api/tasks/dismiss: invalid params -> 400; success -> dismissed count', async () => {
|
||||
const { POST } = await import('@/app/api/tasks/dismiss/route')
|
||||
|
||||
const invalidReq = buildMockRequest({
|
||||
path: '/api/tasks/dismiss',
|
||||
method: 'POST',
|
||||
body: { taskIds: [] },
|
||||
})
|
||||
const invalidRes = await POST(invalidReq, emptyRouteContext)
|
||||
expect(invalidRes.status).toBe(400)
|
||||
|
||||
const req = buildMockRequest({
|
||||
path: '/api/tasks/dismiss',
|
||||
method: 'POST',
|
||||
body: { taskIds: ['task-1', 'task-2'] },
|
||||
})
|
||||
const res = await POST(req, emptyRouteContext)
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
const payload = await res.json() as { success: boolean; dismissed: number }
|
||||
expect(payload.success).toBe(true)
|
||||
expect(payload.dismissed).toBe(1)
|
||||
expect(dismissFailedTasksMock).toHaveBeenCalledWith(['task-1', 'task-2'], 'user-1')
|
||||
})
|
||||
|
||||
it('POST /api/task-target-states: validates payload and returns queried states', async () => {
|
||||
const { POST } = await import('@/app/api/task-target-states/route')
|
||||
|
||||
const invalidReq = buildMockRequest({
|
||||
path: '/api/task-target-states',
|
||||
method: 'POST',
|
||||
body: { projectId: 'project-1' },
|
||||
})
|
||||
const invalidRes = await POST(invalidReq, emptyRouteContext)
|
||||
expect(invalidRes.status).toBe(400)
|
||||
|
||||
const req = buildMockRequest({
|
||||
path: '/api/task-target-states',
|
||||
method: 'POST',
|
||||
body: {
|
||||
projectId: 'project-1',
|
||||
targets: [
|
||||
{
|
||||
targetType: 'CharacterAppearance',
|
||||
targetId: 'appearance-1',
|
||||
types: ['IMAGE_CHARACTER'],
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
const res = await POST(req, emptyRouteContext)
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
const payload = await res.json() as { states: Array<Record<string, unknown>> }
|
||||
expect(payload.states).toHaveLength(1)
|
||||
expect(withPrismaRetryMock).toHaveBeenCalledTimes(1)
|
||||
expect(queryTaskTargetStatesMock).toHaveBeenCalledWith({
|
||||
projectId: 'project-1',
|
||||
userId: 'user-1',
|
||||
targets: [
|
||||
{
|
||||
targetType: 'CharacterAppearance',
|
||||
targetId: 'appearance-1',
|
||||
types: ['IMAGE_CHARACTER'],
|
||||
},
|
||||
],
|
||||
})
|
||||
})
|
||||
|
||||
it('GET /api/tasks/[taskId]: enforces ownership and returns task detail', async () => {
|
||||
const route = await import('@/app/api/tasks/[taskId]/route')
|
||||
|
||||
authState.authenticated = false
|
||||
const unauthorizedReq = buildMockRequest({ path: '/api/tasks/task-1', method: 'GET' })
|
||||
const unauthorizedRes = await route.GET(unauthorizedReq, { params: Promise.resolve({ taskId: 'task-1' }) })
|
||||
expect(unauthorizedRes.status).toBe(401)
|
||||
|
||||
authState.authenticated = true
|
||||
getTaskByIdMock.mockResolvedValueOnce({ ...baseTask, userId: 'other-user' })
|
||||
const notFoundReq = buildMockRequest({ path: '/api/tasks/task-1', method: 'GET' })
|
||||
const notFoundRes = await route.GET(notFoundReq, { params: Promise.resolve({ taskId: 'task-1' }) })
|
||||
expect(notFoundRes.status).toBe(404)
|
||||
|
||||
const req = buildMockRequest({ path: '/api/tasks/task-1', method: 'GET' })
|
||||
const res = await route.GET(req, { params: Promise.resolve({ taskId: 'task-1' }) })
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
const payload = await res.json() as { task: TaskRecord }
|
||||
expect(payload.task.id).toBe('task-1')
|
||||
})
|
||||
|
||||
it('GET /api/tasks/[taskId]?includeEvents=1: returns lifecycle events for refresh replay', async () => {
|
||||
const route = await import('@/app/api/tasks/[taskId]/route')
|
||||
const replayEvents: TaskLifecycleReplayEvent[] = [
|
||||
{
|
||||
id: '11',
|
||||
type: 'task.lifecycle',
|
||||
taskId: 'task-1',
|
||||
projectId: 'project-1',
|
||||
userId: 'user-1',
|
||||
ts: new Date().toISOString(),
|
||||
taskType: 'IMAGE_CHARACTER',
|
||||
targetType: 'CharacterAppearance',
|
||||
targetId: 'appearance-1',
|
||||
episodeId: null,
|
||||
payload: {
|
||||
lifecycleType: 'task.processing',
|
||||
stepId: 'clip_1_phase1',
|
||||
stepTitle: '分镜规划',
|
||||
stepIndex: 1,
|
||||
stepTotal: 3,
|
||||
message: 'running',
|
||||
},
|
||||
},
|
||||
]
|
||||
listTaskLifecycleEventsMock.mockResolvedValueOnce(replayEvents)
|
||||
|
||||
const req = buildMockRequest({
|
||||
path: '/api/tasks/task-1',
|
||||
method: 'GET',
|
||||
query: { includeEvents: '1', eventsLimit: '1200' },
|
||||
})
|
||||
const res = await route.GET(req, { params: Promise.resolve({ taskId: 'task-1' }) })
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
const payload = await res.json() as { task: TaskRecord; events: Array<Record<string, unknown>> }
|
||||
expect(payload.task.id).toBe('task-1')
|
||||
expect(payload.events).toHaveLength(1)
|
||||
expect(payload.events[0]?.id).toBe('11')
|
||||
expect(listTaskLifecycleEventsMock).toHaveBeenCalledWith('task-1', 1200)
|
||||
})
|
||||
|
||||
it('DELETE /api/tasks/[taskId]: cancellation publishes cancelled event payload', async () => {
|
||||
const { DELETE } = await import('@/app/api/tasks/[taskId]/route')
|
||||
|
||||
const req = buildMockRequest({ path: '/api/tasks/task-1', method: 'DELETE' })
|
||||
const res = await DELETE(req, { params: Promise.resolve({ taskId: 'task-1' }) } as RouteContext)
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
expect(removeTaskJobMock).toHaveBeenCalledWith('task-1')
|
||||
expect(publishTaskEventMock).toHaveBeenCalledWith(expect.objectContaining({
|
||||
taskId: 'task-1',
|
||||
projectId: 'project-1',
|
||||
payload: expect.objectContaining({
|
||||
cancelled: true,
|
||||
stage: 'cancelled',
|
||||
}),
|
||||
}))
|
||||
})
|
||||
|
||||
it('GET /api/sse: missing projectId -> 400; unauthenticated with projectId -> 401', async () => {
|
||||
const { GET } = await import('@/app/api/sse/route')
|
||||
|
||||
const invalidReq = buildMockRequest({ path: '/api/sse', method: 'GET' })
|
||||
const invalidRes = await GET(invalidReq, emptyRouteContext)
|
||||
expect(invalidRes.status).toBe(400)
|
||||
|
||||
authState.authenticated = false
|
||||
const unauthorizedReq = buildMockRequest({
|
||||
path: '/api/sse',
|
||||
method: 'GET',
|
||||
query: { projectId: 'project-1' },
|
||||
})
|
||||
const unauthorizedRes = await GET(unauthorizedReq, emptyRouteContext)
|
||||
expect(unauthorizedRes.status).toBe(401)
|
||||
})
|
||||
|
||||
it('GET /api/sse: authenticated replay request returns SSE stream and replays missed events', async () => {
|
||||
const { GET } = await import('@/app/api/sse/route')
|
||||
|
||||
listEventsAfterMock.mockResolvedValueOnce([
|
||||
{
|
||||
id: '4',
|
||||
type: 'task.lifecycle',
|
||||
taskId: 'task-1',
|
||||
projectId: 'project-1',
|
||||
userId: 'user-1',
|
||||
ts: new Date().toISOString(),
|
||||
taskType: 'IMAGE_CHARACTER',
|
||||
targetType: 'CharacterAppearance',
|
||||
targetId: 'appearance-1',
|
||||
episodeId: null,
|
||||
payload: { lifecycleType: 'task.created' },
|
||||
} satisfies ReplayEvent,
|
||||
])
|
||||
|
||||
const req = buildMockRequest({
|
||||
path: '/api/sse',
|
||||
method: 'GET',
|
||||
query: { projectId: 'project-1' },
|
||||
headers: { 'last-event-id': '3' },
|
||||
})
|
||||
const res = await GET(req, emptyRouteContext)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.get('content-type')).toContain('text/event-stream')
|
||||
expect(listEventsAfterMock).toHaveBeenCalledWith('project-1', 3, 5000)
|
||||
expect(addChannelListenerMock).toHaveBeenCalledWith('project:project-1', expect.any(Function))
|
||||
|
||||
const reader = res.body?.getReader()
|
||||
expect(reader).toBeTruthy()
|
||||
const firstChunk = await reader!.read()
|
||||
expect(firstChunk.done).toBe(false)
|
||||
const decoded = new TextDecoder().decode(firstChunk.value)
|
||||
expect(decoded).toContain('event:')
|
||||
await reader!.cancel()
|
||||
})
|
||||
|
||||
it('GET /api/sse: channel lifecycle stream includes terminal completed event', async () => {
|
||||
const { GET } = await import('@/app/api/sse/route')
|
||||
listEventsAfterMock.mockResolvedValueOnce([])
|
||||
|
||||
const req = buildMockRequest({
|
||||
path: '/api/sse',
|
||||
method: 'GET',
|
||||
query: { projectId: 'project-1' },
|
||||
headers: { 'last-event-id': '10' },
|
||||
})
|
||||
const res = await GET(req, emptyRouteContext)
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
const listener = subscriberState.listener
|
||||
expect(listener).toBeTruthy()
|
||||
|
||||
listener!(JSON.stringify({
|
||||
id: '11',
|
||||
type: 'task.lifecycle',
|
||||
taskId: 'task-1',
|
||||
projectId: 'project-1',
|
||||
userId: 'user-1',
|
||||
ts: new Date().toISOString(),
|
||||
taskType: 'IMAGE_CHARACTER',
|
||||
targetType: 'CharacterAppearance',
|
||||
targetId: 'appearance-1',
|
||||
episodeId: null,
|
||||
payload: { lifecycleType: 'processing', progress: 60 },
|
||||
}))
|
||||
listener!(JSON.stringify({
|
||||
id: '12',
|
||||
type: 'task.lifecycle',
|
||||
taskId: 'task-1',
|
||||
projectId: 'project-1',
|
||||
userId: 'user-1',
|
||||
ts: new Date().toISOString(),
|
||||
taskType: 'IMAGE_CHARACTER',
|
||||
targetType: 'CharacterAppearance',
|
||||
targetId: 'appearance-1',
|
||||
episodeId: null,
|
||||
payload: { lifecycleType: 'completed', progress: 100 },
|
||||
}))
|
||||
|
||||
const reader = res.body?.getReader()
|
||||
expect(reader).toBeTruthy()
|
||||
const chunk1 = await reader!.read()
|
||||
const chunk2 = await reader!.read()
|
||||
const merged = `${new TextDecoder().decode(chunk1.value)}${new TextDecoder().decode(chunk2.value)}`
|
||||
|
||||
expect(merged).toContain('"lifecycleType":"processing"')
|
||||
expect(merged).toContain('"lifecycleType":"completed"')
|
||||
expect(merged).toContain('"taskId":"task-1"')
|
||||
await reader!.cancel()
|
||||
})
|
||||
})
|
||||
35
tests/integration/api/helpers/call-route.ts
Normal file
35
tests/integration/api/helpers/call-route.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import { NextRequest } from 'next/server'
|
||||
|
||||
type RouteParams = Record<string, string>
|
||||
type HeaderMap = Record<string, string>
|
||||
|
||||
type RouteHandler = (
|
||||
req: NextRequest,
|
||||
ctx?: { params: Promise<RouteParams> },
|
||||
) => Promise<Response>
|
||||
|
||||
export async function callRoute(
|
||||
handler: RouteHandler,
|
||||
method: 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE',
|
||||
body?: unknown,
|
||||
options?: { headers?: HeaderMap; params?: RouteParams; query?: Record<string, string> },
|
||||
) {
|
||||
const url = new URL('http://localhost:3000/api/test')
|
||||
if (options?.query) {
|
||||
for (const [key, value] of Object.entries(options.query)) {
|
||||
url.searchParams.set(key, value)
|
||||
}
|
||||
}
|
||||
|
||||
const payload = body === undefined ? undefined : JSON.stringify(body)
|
||||
const req = new NextRequest(url, {
|
||||
method,
|
||||
headers: {
|
||||
...(payload ? { 'content-type': 'application/json' } : {}),
|
||||
...(options?.headers || {}),
|
||||
},
|
||||
...(payload ? { body: payload } : {}),
|
||||
})
|
||||
const context = { params: Promise.resolve(options?.params || {}) }
|
||||
return await handler(req, context)
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { buildMockRequest } from '../../../helpers/request'
|
||||
|
||||
const authState = vi.hoisted(() => ({
|
||||
authenticated: true,
|
||||
}))
|
||||
|
||||
const prismaMock = vi.hoisted(() => ({
|
||||
globalCharacter: {
|
||||
findFirst: vi.fn(),
|
||||
},
|
||||
globalCharacterAppearance: {
|
||||
create: vi.fn(async () => ({ id: 'appearance-new' })),
|
||||
findFirst: vi.fn(),
|
||||
update: vi.fn(async () => ({ id: 'appearance-1' })),
|
||||
deleteMany: vi.fn(async () => ({ count: 1 })),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/api-auth', () => {
|
||||
const unauthorized = () => new Response(
|
||||
JSON.stringify({ error: { code: 'UNAUTHORIZED' } }),
|
||||
{ status: 401, headers: { 'content-type': 'application/json' } },
|
||||
)
|
||||
|
||||
return {
|
||||
isErrorResponse: (value: unknown) => value instanceof Response,
|
||||
requireUserAuth: async () => {
|
||||
if (!authState.authenticated) return unauthorized()
|
||||
return { session: { user: { id: 'user-1' } } }
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@/lib/prisma', () => ({
|
||||
prisma: prismaMock,
|
||||
}))
|
||||
|
||||
describe('api specific - asset hub appearances route', () => {
|
||||
const routeContext = { params: Promise.resolve({}) }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
authState.authenticated = true
|
||||
|
||||
prismaMock.globalCharacter.findFirst.mockResolvedValue({
|
||||
id: 'character-1',
|
||||
userId: 'user-1',
|
||||
appearances: [
|
||||
{ id: 'appearance-1', appearanceIndex: 0, artStyle: 'realistic' },
|
||||
],
|
||||
})
|
||||
prismaMock.globalCharacterAppearance.findFirst.mockResolvedValue({
|
||||
id: 'appearance-1',
|
||||
characterId: 'character-1',
|
||||
appearanceIndex: 0,
|
||||
description: 'old description',
|
||||
descriptions: JSON.stringify(['old description', 'variant description']),
|
||||
})
|
||||
})
|
||||
|
||||
it('PATCH preserves description array length instead of rewriting fixed triple entries', async () => {
|
||||
const mod = await import('@/app/api/asset-hub/appearances/route')
|
||||
const req = buildMockRequest({
|
||||
path: '/api/asset-hub/appearances',
|
||||
method: 'PATCH',
|
||||
body: {
|
||||
characterId: 'character-1',
|
||||
appearanceIndex: 0,
|
||||
description: 'updated description',
|
||||
},
|
||||
})
|
||||
|
||||
const res = await mod.PATCH(req, routeContext)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(prismaMock.globalCharacterAppearance.update).toHaveBeenCalledWith({
|
||||
where: { id: 'appearance-1' },
|
||||
data: {
|
||||
description: 'updated description',
|
||||
descriptions: JSON.stringify(['updated description', 'variant description']),
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('POST initializes new appearance with a single description entry', async () => {
|
||||
const mod = await import('@/app/api/asset-hub/appearances/route')
|
||||
const req = buildMockRequest({
|
||||
path: '/api/asset-hub/appearances',
|
||||
method: 'POST',
|
||||
body: {
|
||||
characterId: 'character-1',
|
||||
changeReason: '新造型',
|
||||
description: 'new description',
|
||||
},
|
||||
})
|
||||
|
||||
const res = await mod.POST(req, routeContext)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(prismaMock.globalCharacterAppearance.create).toHaveBeenCalledWith(expect.objectContaining({
|
||||
data: expect.objectContaining({
|
||||
description: 'new description',
|
||||
descriptions: JSON.stringify(['new description']),
|
||||
}),
|
||||
}))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,163 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { buildMockRequest } from '../../../helpers/request'
|
||||
|
||||
const authMock = vi.hoisted(() => ({
|
||||
requireUserAuth: vi.fn(async () => ({
|
||||
session: { user: { id: 'user-1' } },
|
||||
})),
|
||||
isErrorResponse: vi.fn((value: unknown) => value instanceof Response),
|
||||
}))
|
||||
|
||||
const submitTaskMock = vi.hoisted(() => vi.fn<(input: unknown) => Promise<{
|
||||
success: boolean
|
||||
async: boolean
|
||||
taskId: string
|
||||
status: string
|
||||
deduped: boolean
|
||||
}>>(async () => ({
|
||||
success: true,
|
||||
async: true,
|
||||
taskId: 'task-1',
|
||||
status: 'queued',
|
||||
deduped: false,
|
||||
})))
|
||||
|
||||
const configServiceMock = vi.hoisted(() => ({
|
||||
getUserModelConfig: vi.fn(async () => ({
|
||||
analysisModel: null,
|
||||
characterModel: 'img::character',
|
||||
locationModel: 'img::location',
|
||||
storyboardModel: null,
|
||||
editModel: null,
|
||||
videoModel: null,
|
||||
capabilityDefaults: {},
|
||||
})),
|
||||
buildImageBillingPayloadFromUserConfig: vi.fn((input: { basePayload: Record<string, unknown> }) => ({
|
||||
...input.basePayload,
|
||||
})),
|
||||
}))
|
||||
|
||||
const hasOutputMock = vi.hoisted(() => ({
|
||||
hasGlobalCharacterOutput: vi.fn(async () => false),
|
||||
hasGlobalLocationOutput: vi.fn(async () => false),
|
||||
}))
|
||||
|
||||
const billingMock = vi.hoisted(() => ({
|
||||
buildDefaultTaskBillingInfo: vi.fn(() => ({ billable: false })),
|
||||
}))
|
||||
|
||||
const prismaMock = vi.hoisted(() => ({
|
||||
globalCharacterAppearance: {
|
||||
findFirst: vi.fn(),
|
||||
},
|
||||
globalLocation: {
|
||||
findFirst: vi.fn(),
|
||||
findMany: vi.fn(),
|
||||
},
|
||||
globalLocationImage: {
|
||||
findMany: vi.fn(async () => []),
|
||||
createMany: vi.fn(async () => ({})),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/api-auth', () => authMock)
|
||||
vi.mock('@/lib/task/submitter', () => ({ submitTask: submitTaskMock }))
|
||||
vi.mock('@/lib/config-service', () => configServiceMock)
|
||||
vi.mock('@/lib/task/has-output', () => hasOutputMock)
|
||||
vi.mock('@/lib/billing', () => billingMock)
|
||||
vi.mock('@/lib/prisma', () => ({ prisma: prismaMock }))
|
||||
vi.mock('@/lib/task/resolve-locale', () => ({
|
||||
resolveRequiredTaskLocale: vi.fn(() => 'zh'),
|
||||
}))
|
||||
|
||||
describe('api specific - asset hub generate image art style', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('uses persisted appearance artStyle when request payload does not provide one', async () => {
|
||||
prismaMock.globalCharacterAppearance.findFirst.mockResolvedValueOnce({ artStyle: 'realistic' })
|
||||
const mod = await import('@/app/api/asset-hub/generate-image/route')
|
||||
const req = buildMockRequest({
|
||||
path: '/api/asset-hub/generate-image',
|
||||
method: 'POST',
|
||||
body: {
|
||||
type: 'character',
|
||||
id: 'character-1',
|
||||
appearanceIndex: 0,
|
||||
},
|
||||
})
|
||||
|
||||
const res = await mod.POST(req, { params: Promise.resolve({}) })
|
||||
expect(res.status).toBe(200)
|
||||
expect(prismaMock.globalCharacterAppearance.findFirst).toHaveBeenCalled()
|
||||
const submitArg = submitTaskMock.mock.calls[0]?.[0] as { payload?: Record<string, unknown> } | undefined
|
||||
expect(submitArg?.payload?.artStyle).toBe('realistic')
|
||||
})
|
||||
|
||||
it('uses persisted location artStyle when request payload does not provide one', async () => {
|
||||
prismaMock.globalLocation.findFirst
|
||||
.mockResolvedValueOnce({ artStyle: 'japanese-anime' })
|
||||
.mockResolvedValueOnce({ name: 'Location 1', summary: 'Summary 1' })
|
||||
const mod = await import('@/app/api/asset-hub/generate-image/route')
|
||||
const req = buildMockRequest({
|
||||
path: '/api/asset-hub/generate-image',
|
||||
method: 'POST',
|
||||
body: {
|
||||
type: 'location',
|
||||
id: 'location-1',
|
||||
},
|
||||
})
|
||||
|
||||
const res = await mod.POST(req, { params: Promise.resolve({}) })
|
||||
expect(res.status).toBe(200)
|
||||
expect(prismaMock.globalLocation.findFirst).toHaveBeenCalled()
|
||||
const submitArg = submitTaskMock.mock.calls[0]?.[0] as { payload?: Record<string, unknown> } | undefined
|
||||
expect(submitArg?.payload?.artStyle).toBe('japanese-anime')
|
||||
expect(submitArg?.payload?.count).toBe(3)
|
||||
})
|
||||
|
||||
it('fails with invalid params when persisted artStyle is missing', async () => {
|
||||
prismaMock.globalCharacterAppearance.findFirst.mockResolvedValueOnce({ artStyle: null })
|
||||
const mod = await import('@/app/api/asset-hub/generate-image/route')
|
||||
const req = buildMockRequest({
|
||||
path: '/api/asset-hub/generate-image',
|
||||
method: 'POST',
|
||||
body: {
|
||||
type: 'character',
|
||||
id: 'character-1',
|
||||
appearanceIndex: 0,
|
||||
},
|
||||
})
|
||||
|
||||
const res = await mod.POST(req, { params: Promise.resolve({}) })
|
||||
const body = await res.json()
|
||||
expect(res.status).toBe(400)
|
||||
expect(body.error.code).toBe('INVALID_PARAMS')
|
||||
expect(submitTaskMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('forwards requested count into asset hub image task payload', async () => {
|
||||
prismaMock.globalCharacterAppearance.findFirst.mockResolvedValueOnce({ artStyle: 'realistic' })
|
||||
const mod = await import('@/app/api/asset-hub/generate-image/route')
|
||||
const req = buildMockRequest({
|
||||
path: '/api/asset-hub/generate-image',
|
||||
method: 'POST',
|
||||
body: {
|
||||
type: 'character',
|
||||
id: 'character-1',
|
||||
appearanceIndex: 0,
|
||||
count: 5,
|
||||
},
|
||||
})
|
||||
|
||||
const res = await mod.POST(req, { params: Promise.resolve({}) })
|
||||
expect(res.status).toBe(200)
|
||||
const submitArg = submitTaskMock.mock.calls[0]?.[0] as {
|
||||
payload?: Record<string, unknown>
|
||||
dedupeKey?: string
|
||||
} | undefined
|
||||
expect(submitArg?.payload?.count).toBe(5)
|
||||
expect(submitArg?.dedupeKey).toContain(':5')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,59 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { buildMockRequest } from '../../../helpers/request'
|
||||
|
||||
const authMock = vi.hoisted(() => ({
|
||||
requireUserAuth: vi.fn(async () => ({
|
||||
session: { user: { id: 'user-1' } },
|
||||
})),
|
||||
isErrorResponse: vi.fn((value: unknown) => value instanceof Response),
|
||||
}))
|
||||
|
||||
const prismaMock = vi.hoisted(() => ({
|
||||
globalAssetFolder: {
|
||||
findUnique: vi.fn(async () => null),
|
||||
},
|
||||
globalLocation: {
|
||||
create: vi.fn(async () => ({ id: 'location-1' })),
|
||||
findUnique: vi.fn(async () => ({ id: 'location-1', images: [] })),
|
||||
},
|
||||
globalLocationImage: {
|
||||
createMany: vi.fn<(input: { data: Array<{ imageIndex: number }> }) => Promise<{ count: number }>>(
|
||||
async () => ({ count: 0 }),
|
||||
),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/api-auth', () => authMock)
|
||||
vi.mock('@/lib/prisma', () => ({ prisma: prismaMock }))
|
||||
|
||||
describe('api specific - asset hub location create', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('does not auto-generate images after creating location', async () => {
|
||||
const fetchMock = vi.fn<(input: RequestInfo | URL, init?: RequestInit) => Promise<Response>>(
|
||||
async () => new Response(JSON.stringify({ ok: true }), { status: 200 }),
|
||||
)
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
const mod = await import('@/app/api/asset-hub/locations/route')
|
||||
const req = buildMockRequest({
|
||||
path: '/api/asset-hub/locations',
|
||||
method: 'POST',
|
||||
body: {
|
||||
name: 'Old Town',
|
||||
summary: '雨夜街道',
|
||||
artStyle: 'realistic',
|
||||
},
|
||||
})
|
||||
|
||||
const res = await mod.POST(req, { params: Promise.resolve({}) })
|
||||
expect(res.status).toBe(200)
|
||||
const createManyArg = prismaMock.globalLocationImage.createMany.mock.calls[0]?.[0] as {
|
||||
data?: Array<{ imageIndex: number }>
|
||||
} | undefined
|
||||
expect(createManyArg?.data?.map((item) => item.imageIndex)).toEqual([0])
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,122 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { buildMockRequest } from '../../../helpers/request'
|
||||
|
||||
const authMock = vi.hoisted(() => ({
|
||||
requireUserAuth: vi.fn<() => Promise<{ session: { user: { id: string } } } | Response>>(async () => ({
|
||||
session: { user: { id: 'user-1' } },
|
||||
})),
|
||||
isErrorResponse: vi.fn((value: unknown) => value instanceof Response),
|
||||
}))
|
||||
|
||||
const prismaMock = vi.hoisted(() => ({
|
||||
globalAssetFolder: {
|
||||
findUnique: vi.fn(),
|
||||
},
|
||||
globalCharacter: {
|
||||
create: vi.fn(async () => ({ id: 'character-1', userId: 'user-1' })),
|
||||
findUnique: vi.fn(async () => ({
|
||||
id: 'character-1',
|
||||
userId: 'user-1',
|
||||
name: 'Hero',
|
||||
appearances: [],
|
||||
})),
|
||||
},
|
||||
globalCharacterAppearance: {
|
||||
create: vi.fn(async () => ({ id: 'appearance-1' })),
|
||||
},
|
||||
}))
|
||||
|
||||
const mediaAttachMock = vi.hoisted(() => ({
|
||||
attachMediaFieldsToGlobalCharacter: vi.fn(async (value: unknown) => value),
|
||||
}))
|
||||
|
||||
const mediaServiceMock = vi.hoisted(() => ({
|
||||
resolveMediaRefFromLegacyValue: vi.fn(async () => null),
|
||||
}))
|
||||
|
||||
const envMock = vi.hoisted(() => ({
|
||||
getBaseUrl: vi.fn(() => 'http://localhost:3000'),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/api-auth', () => authMock)
|
||||
vi.mock('@/lib/prisma', () => ({ prisma: prismaMock }))
|
||||
vi.mock('@/lib/media/attach', () => mediaAttachMock)
|
||||
vi.mock('@/lib/media/service', () => mediaServiceMock)
|
||||
vi.mock('@/lib/env', () => envMock)
|
||||
|
||||
describe('api specific - characters POST forwarding to reference task', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
prismaMock.globalAssetFolder.findUnique.mockResolvedValue(null)
|
||||
})
|
||||
|
||||
it('forwards locale and accept-language into background reference task payload', async () => {
|
||||
const fetchMock = vi.fn<(input: RequestInfo | URL, init?: RequestInit) => Promise<Response>>(
|
||||
async () => new Response(JSON.stringify({ ok: true }), { status: 200 }),
|
||||
)
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
const mod = await import('@/app/api/asset-hub/characters/route')
|
||||
const req = buildMockRequest({
|
||||
path: '/api/asset-hub/characters',
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'accept-language': 'zh-CN,zh;q=0.9',
|
||||
},
|
||||
body: {
|
||||
name: 'Hero',
|
||||
artStyle: 'realistic',
|
||||
generateFromReference: true,
|
||||
referenceImageUrl: 'https://example.com/ref.png',
|
||||
customDescription: '冷静,黑发',
|
||||
count: 5,
|
||||
},
|
||||
})
|
||||
|
||||
const res = await mod.POST(req, { params: Promise.resolve({}) })
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
const calledUrl = fetchMock.mock.calls[0]?.[0]
|
||||
const calledInit = fetchMock.mock.calls[0]?.[1] as RequestInit | undefined
|
||||
expect(String(calledUrl)).toContain('/api/asset-hub/reference-to-character')
|
||||
expect((calledInit?.headers as Record<string, string>)['Accept-Language']).toBe('zh-CN,zh;q=0.9')
|
||||
|
||||
const rawBody = calledInit?.body
|
||||
expect(typeof rawBody).toBe('string')
|
||||
const forwarded = JSON.parse(String(rawBody)) as {
|
||||
locale?: string
|
||||
meta?: { locale?: string }
|
||||
customDescription?: string
|
||||
artStyle?: string
|
||||
referenceImageUrls?: string[]
|
||||
appearanceId?: string
|
||||
characterId?: string
|
||||
count?: number
|
||||
}
|
||||
|
||||
expect(forwarded.locale).toBe('zh')
|
||||
expect(forwarded.meta?.locale).toBe('zh')
|
||||
expect(forwarded.customDescription).toBe('冷静,黑发')
|
||||
expect(forwarded.artStyle).toBe('realistic')
|
||||
expect(forwarded.referenceImageUrls).toEqual(['https://example.com/ref.png'])
|
||||
expect(forwarded.characterId).toBe('character-1')
|
||||
expect(forwarded.appearanceId).toBe('appearance-1')
|
||||
expect(forwarded.count).toBe(5)
|
||||
})
|
||||
|
||||
it('returns unauthorized when auth fails', async () => {
|
||||
authMock.requireUserAuth.mockResolvedValueOnce(
|
||||
NextResponse.json({ error: { code: 'UNAUTHORIZED' } }, { status: 401 }),
|
||||
)
|
||||
const mod = await import('@/app/api/asset-hub/characters/route')
|
||||
const req = buildMockRequest({
|
||||
path: '/api/asset-hub/characters',
|
||||
method: 'POST',
|
||||
body: { name: 'Hero' },
|
||||
})
|
||||
|
||||
const res = await mod.POST(req, { params: Promise.resolve({}) })
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
})
|
||||
61
tests/integration/api/specific/characters-post.test.ts
Normal file
61
tests/integration/api/specific/characters-post.test.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { buildMockRequest } from '../../../helpers/request'
|
||||
import {
|
||||
installAuthMocks,
|
||||
mockAuthenticated,
|
||||
mockUnauthenticated,
|
||||
resetAuthMockState,
|
||||
} from '../../../helpers/auth'
|
||||
|
||||
describe('api specific - characters POST', () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules()
|
||||
resetAuthMockState()
|
||||
})
|
||||
|
||||
it('returns unauthorized when user is not authenticated', async () => {
|
||||
installAuthMocks()
|
||||
mockUnauthenticated()
|
||||
const mod = await import('@/app/api/asset-hub/characters/route')
|
||||
const req = buildMockRequest({
|
||||
path: '/api/asset-hub/characters',
|
||||
method: 'POST',
|
||||
body: { name: 'A' },
|
||||
})
|
||||
|
||||
const res = await mod.POST(req, { params: Promise.resolve({}) })
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns invalid params when name is missing', async () => {
|
||||
installAuthMocks()
|
||||
mockAuthenticated('user-a')
|
||||
const mod = await import('@/app/api/asset-hub/characters/route')
|
||||
const req = buildMockRequest({
|
||||
path: '/api/asset-hub/characters',
|
||||
method: 'POST',
|
||||
body: {},
|
||||
})
|
||||
|
||||
const res = await mod.POST(req, { params: Promise.resolve({}) })
|
||||
const body = await res.json()
|
||||
expect(res.status).toBe(400)
|
||||
expect(body.error.code).toBe('INVALID_PARAMS')
|
||||
})
|
||||
|
||||
it('returns invalid params when artStyle is missing', async () => {
|
||||
installAuthMocks()
|
||||
mockAuthenticated('user-a')
|
||||
const mod = await import('@/app/api/asset-hub/characters/route')
|
||||
const req = buildMockRequest({
|
||||
path: '/api/asset-hub/characters',
|
||||
method: 'POST',
|
||||
body: { name: 'Hero' },
|
||||
})
|
||||
|
||||
const res = await mod.POST(req, { params: Promise.resolve({}) })
|
||||
const body = await res.json()
|
||||
expect(res.status).toBe(400)
|
||||
expect(body.error.code).toBe('INVALID_PARAMS')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,89 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { buildMockRequest } from '../../../helpers/request'
|
||||
|
||||
const authMock = vi.hoisted(() => ({
|
||||
requireProjectAuth: vi.fn(async () => ({
|
||||
session: { user: { id: 'user-1' } },
|
||||
novelData: { id: 'novel-data-1' },
|
||||
})),
|
||||
requireProjectAuthLight: vi.fn(),
|
||||
isErrorResponse: vi.fn((value: unknown) => value instanceof Response),
|
||||
}))
|
||||
|
||||
const prismaMock = vi.hoisted(() => ({
|
||||
novelPromotionCharacter: {
|
||||
create: vi.fn(async () => ({ id: 'character-1' })),
|
||||
findUnique: vi.fn(async () => ({ id: 'character-1', appearances: [] })),
|
||||
},
|
||||
characterAppearance: {
|
||||
create: vi.fn(async () => ({ id: 'appearance-1' })),
|
||||
},
|
||||
}))
|
||||
|
||||
const envMock = vi.hoisted(() => ({
|
||||
getBaseUrl: vi.fn(() => 'http://localhost:3000'),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/api-auth', () => authMock)
|
||||
vi.mock('@/lib/prisma', () => ({ prisma: prismaMock }))
|
||||
vi.mock('@/lib/env', () => envMock)
|
||||
vi.mock('@/lib/task/resolve-locale', () => ({
|
||||
resolveTaskLocale: vi.fn(() => 'zh'),
|
||||
}))
|
||||
|
||||
describe('api specific - novel promotion character style forwarding', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('does not auto-generate images when creating by text prompt', async () => {
|
||||
const fetchMock = vi.fn<(input: RequestInfo | URL, init?: RequestInit) => Promise<Response>>(
|
||||
async () => new Response(JSON.stringify({ ok: true }), { status: 200 }),
|
||||
)
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
const mod = await import('@/app/api/novel-promotion/[projectId]/character/route')
|
||||
const req = buildMockRequest({
|
||||
path: '/api/novel-promotion/project-1/character',
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'accept-language': 'zh-CN,zh;q=0.9',
|
||||
},
|
||||
body: {
|
||||
name: 'Hero',
|
||||
description: '主角设定',
|
||||
artStyle: 'realistic',
|
||||
count: 4,
|
||||
},
|
||||
})
|
||||
|
||||
const res = await mod.POST(req, { params: Promise.resolve({ projectId: 'project-1' }) })
|
||||
expect(res.status).toBe(200)
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects invalid artStyle before creating character', async () => {
|
||||
const fetchMock = vi.fn<(input: RequestInfo | URL, init?: RequestInit) => Promise<Response>>(
|
||||
async () => new Response(JSON.stringify({ ok: true }), { status: 200 }),
|
||||
)
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
const mod = await import('@/app/api/novel-promotion/[projectId]/character/route')
|
||||
const req = buildMockRequest({
|
||||
path: '/api/novel-promotion/project-1/character',
|
||||
method: 'POST',
|
||||
body: {
|
||||
name: 'Hero',
|
||||
description: '主角设定',
|
||||
artStyle: 'anime',
|
||||
},
|
||||
})
|
||||
|
||||
const res = await mod.POST(req, { params: Promise.resolve({ projectId: 'project-1' }) })
|
||||
const body = await res.json()
|
||||
expect(res.status).toBe(400)
|
||||
expect(body.error.code).toBe('INVALID_PARAMS')
|
||||
expect(prismaMock.novelPromotionCharacter.create).not.toHaveBeenCalled()
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,129 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { buildMockRequest } from '../../../helpers/request'
|
||||
|
||||
const authMock = vi.hoisted(() => ({
|
||||
requireProjectAuthLight: vi.fn(async () => ({
|
||||
session: { user: { id: 'user-1' } },
|
||||
})),
|
||||
isErrorResponse: vi.fn((value: unknown) => value instanceof Response),
|
||||
}))
|
||||
|
||||
const submitTaskMock = vi.hoisted(() => vi.fn<(input: unknown) => Promise<{
|
||||
success: boolean
|
||||
async: boolean
|
||||
taskId: string
|
||||
status: string
|
||||
deduped: boolean
|
||||
}>>(async () => ({
|
||||
success: true,
|
||||
async: true,
|
||||
taskId: 'task-1',
|
||||
status: 'queued',
|
||||
deduped: false,
|
||||
})))
|
||||
|
||||
const configServiceMock = vi.hoisted(() => ({
|
||||
getProjectModelConfig: vi.fn(async () => ({
|
||||
analysisModel: null,
|
||||
characterModel: 'img::character',
|
||||
locationModel: 'img::location',
|
||||
storyboardModel: null,
|
||||
editModel: null,
|
||||
videoModel: null,
|
||||
videoRatio: '16:9',
|
||||
artStyle: 'american-comic',
|
||||
capabilityDefaults: {},
|
||||
capabilityOverrides: {},
|
||||
})),
|
||||
buildImageBillingPayload: vi.fn(async (input: { basePayload: Record<string, unknown> }) => ({
|
||||
...input.basePayload,
|
||||
})),
|
||||
}))
|
||||
|
||||
const hasOutputMock = vi.hoisted(() => ({
|
||||
hasCharacterAppearanceOutput: vi.fn(async () => false),
|
||||
hasLocationImageOutput: vi.fn(async () => false),
|
||||
}))
|
||||
|
||||
const billingMock = vi.hoisted(() => ({
|
||||
buildDefaultTaskBillingInfo: vi.fn(() => ({ billable: false })),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/api-auth', () => authMock)
|
||||
vi.mock('@/lib/task/submitter', () => ({ submitTask: submitTaskMock }))
|
||||
vi.mock('@/lib/config-service', () => configServiceMock)
|
||||
vi.mock('@/lib/task/has-output', () => hasOutputMock)
|
||||
vi.mock('@/lib/billing', () => billingMock)
|
||||
vi.mock('@/lib/task/resolve-locale', () => ({
|
||||
resolveRequiredTaskLocale: vi.fn(() => 'zh'),
|
||||
}))
|
||||
|
||||
describe('api specific - novel promotion generate image art style', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('accepts valid artStyle and forwards it into task payload', async () => {
|
||||
const mod = await import('@/app/api/novel-promotion/[projectId]/generate-image/route')
|
||||
const req = buildMockRequest({
|
||||
path: '/api/novel-promotion/project-1/generate-image',
|
||||
method: 'POST',
|
||||
body: {
|
||||
type: 'character',
|
||||
id: 'character-1',
|
||||
appearanceId: 'appearance-1',
|
||||
artStyle: 'realistic',
|
||||
},
|
||||
})
|
||||
|
||||
const res = await mod.POST(req, { params: Promise.resolve({ projectId: 'project-1' }) })
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
const submitArg = submitTaskMock.mock.calls[0]?.[0] as { payload?: Record<string, unknown> } | undefined
|
||||
expect(submitArg?.payload?.artStyle).toBe('realistic')
|
||||
})
|
||||
|
||||
it('rejects invalid artStyle with invalid params', async () => {
|
||||
const mod = await import('@/app/api/novel-promotion/[projectId]/generate-image/route')
|
||||
const req = buildMockRequest({
|
||||
path: '/api/novel-promotion/project-1/generate-image',
|
||||
method: 'POST',
|
||||
body: {
|
||||
type: 'character',
|
||||
id: 'character-1',
|
||||
appearanceId: 'appearance-1',
|
||||
artStyle: 'anime',
|
||||
},
|
||||
})
|
||||
|
||||
const res = await mod.POST(req, { params: Promise.resolve({ projectId: 'project-1' }) })
|
||||
const body = await res.json()
|
||||
expect(res.status).toBe(400)
|
||||
expect(body.error.code).toBe('INVALID_PARAMS')
|
||||
expect(submitTaskMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('forwards requested count into task payload and dedupe key', async () => {
|
||||
const mod = await import('@/app/api/novel-promotion/[projectId]/generate-image/route')
|
||||
const req = buildMockRequest({
|
||||
path: '/api/novel-promotion/project-1/generate-image',
|
||||
method: 'POST',
|
||||
body: {
|
||||
type: 'character',
|
||||
id: 'character-1',
|
||||
appearanceId: 'appearance-1',
|
||||
count: 6,
|
||||
},
|
||||
})
|
||||
|
||||
const res = await mod.POST(req, { params: Promise.resolve({ projectId: 'project-1' }) })
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
const submitArg = submitTaskMock.mock.calls[0]?.[0] as {
|
||||
payload?: Record<string, unknown>
|
||||
dedupeKey?: string
|
||||
} | undefined
|
||||
expect(submitArg?.payload?.count).toBe(6)
|
||||
expect(submitArg?.dedupeKey).toBe('image_character:appearance-1:6')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,118 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { buildMockRequest } from '../../../helpers/request'
|
||||
|
||||
const authMock = vi.hoisted(() => ({
|
||||
requireProjectAuth: vi.fn(async () => ({
|
||||
session: { user: { id: 'user-1' } },
|
||||
novelData: { id: 'novel-data-1' },
|
||||
})),
|
||||
requireProjectAuthLight: vi.fn(),
|
||||
isErrorResponse: vi.fn((value: unknown) => value instanceof Response),
|
||||
}))
|
||||
|
||||
const prismaMock = vi.hoisted(() => ({
|
||||
novelPromotionLocation: {
|
||||
create: vi.fn(async () => ({ id: 'location-1' })),
|
||||
findUnique: vi.fn(async () => ({ id: 'location-1', images: [] })),
|
||||
},
|
||||
locationImage: {
|
||||
createMany: vi.fn<(input: { data: Array<{ imageIndex: number }> }) => Promise<{ count: number }>>(
|
||||
async () => ({ count: 0 }),
|
||||
),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/api-auth', () => authMock)
|
||||
vi.mock('@/lib/prisma', () => ({ prisma: prismaMock }))
|
||||
vi.mock('@/lib/task/resolve-locale', () => ({
|
||||
resolveTaskLocale: vi.fn(() => 'zh'),
|
||||
}))
|
||||
|
||||
describe('api specific - novel promotion location style forwarding', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('does not auto-generate images when creating location', async () => {
|
||||
const fetchMock = vi.fn<(input: RequestInfo | URL, init?: RequestInit) => Promise<Response>>(
|
||||
async () => new Response(JSON.stringify({ ok: true }), { status: 200 }),
|
||||
)
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
const mod = await import('@/app/api/novel-promotion/[projectId]/location/route')
|
||||
const req = buildMockRequest({
|
||||
path: '/api/novel-promotion/project-1/location',
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'accept-language': 'zh-CN,zh;q=0.9',
|
||||
},
|
||||
body: {
|
||||
name: 'Old Town',
|
||||
description: '雨夜街道',
|
||||
artStyle: 'realistic',
|
||||
},
|
||||
})
|
||||
|
||||
const res = await mod.POST(req, { params: Promise.resolve({ projectId: 'project-1' }) })
|
||||
expect(res.status).toBe(200)
|
||||
const createManyArg = prismaMock.locationImage.createMany.mock.calls[0]?.[0] as {
|
||||
data?: Array<{ imageIndex: number }>
|
||||
} | undefined
|
||||
expect(createManyArg?.data?.map((item) => item.imageIndex)).toEqual([0])
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects invalid artStyle before creating location', async () => {
|
||||
const fetchMock = vi.fn<(input: RequestInfo | URL, init?: RequestInit) => Promise<Response>>(
|
||||
async () => new Response(JSON.stringify({ ok: true }), { status: 200 }),
|
||||
)
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
const mod = await import('@/app/api/novel-promotion/[projectId]/location/route')
|
||||
const req = buildMockRequest({
|
||||
path: '/api/novel-promotion/project-1/location',
|
||||
method: 'POST',
|
||||
body: {
|
||||
name: 'Old Town',
|
||||
description: '雨夜街道',
|
||||
artStyle: 'anime',
|
||||
},
|
||||
})
|
||||
|
||||
const res = await mod.POST(req, { params: Promise.resolve({ projectId: 'project-1' }) })
|
||||
const body = await res.json()
|
||||
expect(res.status).toBe(400)
|
||||
expect(body.error.code).toBe('INVALID_PARAMS')
|
||||
expect(prismaMock.novelPromotionLocation.create).not.toHaveBeenCalled()
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('creates requested number of slots and forwards count', async () => {
|
||||
const fetchMock = vi.fn<(input: RequestInfo | URL, init?: RequestInit) => Promise<Response>>(
|
||||
async () => new Response(JSON.stringify({ ok: true }), { status: 200 }),
|
||||
)
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
const mod = await import('@/app/api/novel-promotion/[projectId]/location/route')
|
||||
const req = buildMockRequest({
|
||||
path: '/api/novel-promotion/project-1/location',
|
||||
method: 'POST',
|
||||
body: {
|
||||
name: 'Old Town',
|
||||
description: '雨夜街道',
|
||||
artStyle: 'realistic',
|
||||
count: 5,
|
||||
},
|
||||
})
|
||||
|
||||
const res = await mod.POST(req, { params: Promise.resolve({ projectId: 'project-1' }) })
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
const createManyArg = prismaMock.locationImage.createMany.mock.calls[0]?.[0] as {
|
||||
data?: Array<{ imageIndex: number }>
|
||||
} | undefined
|
||||
expect(createManyArg?.data?.map((item) => item.imageIndex)).toEqual([0, 1, 2, 3, 4])
|
||||
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,132 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { buildMockRequest } from '../../../helpers/request'
|
||||
|
||||
const authMock = vi.hoisted(() => ({
|
||||
requireProjectAuthLight: vi.fn(async () => ({
|
||||
session: { user: { id: 'user-1', name: 'User 1' } },
|
||||
project: { id: 'project-1', userId: 'user-1', mode: 'novel-promotion', name: 'Project 1' },
|
||||
})),
|
||||
isErrorResponse: vi.fn((value: unknown) => value instanceof Response),
|
||||
}))
|
||||
|
||||
const prismaMock = vi.hoisted(() => ({
|
||||
novelPromotionProject: {
|
||||
findUnique: vi.fn(async () => ({
|
||||
analysisModel: 'llm::analysis',
|
||||
characterModel: 'img::character',
|
||||
locationModel: 'img::location',
|
||||
storyboardModel: 'img::storyboard',
|
||||
editModel: 'img::edit',
|
||||
videoModel: 'video::model',
|
||||
audioModel: 'audio::model',
|
||||
})),
|
||||
update: vi.fn(async () => ({
|
||||
id: 'np-1',
|
||||
artStyle: 'realistic',
|
||||
})),
|
||||
},
|
||||
userPreference: {
|
||||
upsert: vi.fn(async () => ({ userId: 'user-1', artStyle: 'realistic' })),
|
||||
},
|
||||
}))
|
||||
|
||||
const mediaAttachMock = vi.hoisted(() => ({
|
||||
attachMediaFieldsToProject: vi.fn(async (value: unknown) => value),
|
||||
}))
|
||||
|
||||
const logMock = vi.hoisted(() => ({
|
||||
logProjectAction: vi.fn(),
|
||||
}))
|
||||
|
||||
const modelConfigContractMock = vi.hoisted(() => ({
|
||||
parseModelKeyStrict: vi.fn(() => ({ provider: 'mock', modelId: 'mock-model' })),
|
||||
}))
|
||||
|
||||
const capabilityLookupMock = vi.hoisted(() => ({
|
||||
resolveBuiltinModelContext: vi.fn(() => null),
|
||||
getCapabilityOptionFields: vi.fn(() => ({})),
|
||||
validateCapabilitySelectionsPayload: vi.fn(() => []),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/api-auth', () => authMock)
|
||||
vi.mock('@/lib/prisma', () => ({ prisma: prismaMock }))
|
||||
vi.mock('@/lib/media/attach', () => mediaAttachMock)
|
||||
vi.mock('@/lib/logging/semantic', () => logMock)
|
||||
vi.mock('@/lib/model-config-contract', () => modelConfigContractMock)
|
||||
vi.mock('@/lib/model-capabilities/lookup', () => capabilityLookupMock)
|
||||
|
||||
describe('api specific - novel promotion project art style validation', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('accepts valid artStyle and syncs to user preference', async () => {
|
||||
const mod = await import('@/app/api/novel-promotion/[projectId]/route')
|
||||
const req = buildMockRequest({
|
||||
path: '/api/novel-promotion/project-1',
|
||||
method: 'PATCH',
|
||||
body: {
|
||||
artStyle: ' realistic ',
|
||||
},
|
||||
})
|
||||
|
||||
const res = await mod.PATCH(req, { params: Promise.resolve({ projectId: 'project-1' }) })
|
||||
expect(res.status).toBe(200)
|
||||
expect(prismaMock.novelPromotionProject.update).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
data: expect.objectContaining({ artStyle: 'realistic' }),
|
||||
}),
|
||||
)
|
||||
expect(prismaMock.userPreference.upsert).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
update: expect.objectContaining({ artStyle: 'realistic' }),
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('rejects invalid artStyle with invalid params', async () => {
|
||||
const mod = await import('@/app/api/novel-promotion/[projectId]/route')
|
||||
const req = buildMockRequest({
|
||||
path: '/api/novel-promotion/project-1',
|
||||
method: 'PATCH',
|
||||
body: {
|
||||
artStyle: 'anime',
|
||||
},
|
||||
})
|
||||
|
||||
const res = await mod.PATCH(req, { params: Promise.resolve({ projectId: 'project-1' }) })
|
||||
const body = await res.json()
|
||||
expect(res.status).toBe(400)
|
||||
expect(body.error.code).toBe('INVALID_PARAMS')
|
||||
expect(prismaMock.novelPromotionProject.update).not.toHaveBeenCalled()
|
||||
expect(prismaMock.userPreference.upsert).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('accepts audioModel and syncs it to user preference', async () => {
|
||||
const mod = await import('@/app/api/novel-promotion/[projectId]/route')
|
||||
const req = buildMockRequest({
|
||||
path: '/api/novel-promotion/project-1',
|
||||
method: 'PATCH',
|
||||
body: {
|
||||
audioModel: 'bailian::qwen3-tts-vd-2026-01-26',
|
||||
},
|
||||
})
|
||||
|
||||
const res = await mod.PATCH(req, { params: Promise.resolve({ projectId: 'project-1' }) })
|
||||
expect(res.status).toBe(200)
|
||||
expect(prismaMock.novelPromotionProject.update).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
data: expect.objectContaining({
|
||||
audioModel: 'bailian::qwen3-tts-vd-2026-01-26',
|
||||
}),
|
||||
}),
|
||||
)
|
||||
expect(prismaMock.userPreference.upsert).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
update: expect.objectContaining({
|
||||
audioModel: 'bailian::qwen3-tts-vd-2026-01-26',
|
||||
}),
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,70 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { buildMockRequest } from '../../../helpers/request'
|
||||
|
||||
const authMock = vi.hoisted(() => ({
|
||||
requireUserAuth: vi.fn(async () => ({
|
||||
session: { user: { id: 'user-1' } },
|
||||
})),
|
||||
isErrorResponse: vi.fn((value: unknown) => value instanceof Response),
|
||||
}))
|
||||
|
||||
const prismaMock = vi.hoisted(() => ({
|
||||
userPreference: {
|
||||
findUnique: vi.fn(async () => ({
|
||||
analysisModel: 'llm::analysis',
|
||||
characterModel: 'img::character',
|
||||
locationModel: 'img::location',
|
||||
storyboardModel: 'img::storyboard',
|
||||
editModel: 'img::edit',
|
||||
videoModel: 'video::model',
|
||||
audioModel: 'audio::tts',
|
||||
videoRatio: '9:16',
|
||||
artStyle: 'realistic',
|
||||
ttsRate: '+0%',
|
||||
})),
|
||||
},
|
||||
project: {
|
||||
create: vi.fn(async () => ({
|
||||
id: 'project-1',
|
||||
name: 'Test Project',
|
||||
description: null,
|
||||
mode: 'novel-promotion',
|
||||
userId: 'user-1',
|
||||
})),
|
||||
},
|
||||
novelPromotionProject: {
|
||||
create: vi.fn(async () => ({ id: 'np-1', projectId: 'project-1' })),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/api-auth', () => authMock)
|
||||
vi.mock('@/lib/prisma', () => ({ prisma: prismaMock }))
|
||||
|
||||
describe('api specific - project create default audio model', () => {
|
||||
const routeContext = { params: Promise.resolve({}) }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('copies user preference audioModel into the new novel promotion project', async () => {
|
||||
const mod = await import('@/app/api/projects/route')
|
||||
const req = buildMockRequest({
|
||||
path: '/api/projects',
|
||||
method: 'POST',
|
||||
body: {
|
||||
name: 'Test Project',
|
||||
description: '',
|
||||
},
|
||||
})
|
||||
|
||||
const res = await mod.POST(req, routeContext)
|
||||
expect(res.status).toBe(201)
|
||||
expect(prismaMock.novelPromotionProject.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({
|
||||
projectId: 'project-1',
|
||||
audioModel: 'audio::tts',
|
||||
}),
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,47 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { buildMockRequest } from '../../../helpers/request'
|
||||
import {
|
||||
installAuthMocks,
|
||||
mockAuthenticated,
|
||||
mockUnauthenticated,
|
||||
resetAuthMockState,
|
||||
} from '../../../helpers/auth'
|
||||
|
||||
describe('api specific - reference to character route', () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules()
|
||||
resetAuthMockState()
|
||||
})
|
||||
|
||||
it('returns unauthorized when user is not authenticated', async () => {
|
||||
installAuthMocks()
|
||||
mockUnauthenticated()
|
||||
const mod = await import('@/app/api/asset-hub/reference-to-character/route')
|
||||
const req = buildMockRequest({
|
||||
path: '/api/asset-hub/reference-to-character',
|
||||
method: 'POST',
|
||||
body: {
|
||||
referenceImageUrl: 'https://example.com/ref.png',
|
||||
},
|
||||
})
|
||||
|
||||
const res = await mod.POST(req, { params: Promise.resolve({}) })
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns invalid params when references are missing', async () => {
|
||||
installAuthMocks()
|
||||
mockAuthenticated('user-a')
|
||||
const mod = await import('@/app/api/asset-hub/reference-to-character/route')
|
||||
const req = buildMockRequest({
|
||||
path: '/api/asset-hub/reference-to-character',
|
||||
method: 'POST',
|
||||
body: {},
|
||||
})
|
||||
|
||||
const res = await mod.POST(req, { params: Promise.resolve({}) })
|
||||
const body = await res.json()
|
||||
expect(res.status).toBe(400)
|
||||
expect(body.error.code).toBe('INVALID_PARAMS')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,134 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { buildMockRequest } from '../../../helpers/request'
|
||||
|
||||
const authMock = vi.hoisted(() => ({
|
||||
requireProjectAuthLight: vi.fn(async () => ({
|
||||
session: { user: { id: 'user-1' } },
|
||||
project: { id: 'project-1', userId: 'user-1', mode: 'novel-promotion' },
|
||||
})),
|
||||
isErrorResponse: vi.fn((value: unknown) => value instanceof Response),
|
||||
}))
|
||||
|
||||
const prismaMock = vi.hoisted(() => ({
|
||||
novelPromotionProject: {
|
||||
findUnique: vi.fn(async () => ({ id: 'np-1' })),
|
||||
},
|
||||
novelPromotionEpisode: {
|
||||
findUnique: vi.fn(async () => ({
|
||||
id: 'episode-1',
|
||||
speakerVoices: '{}',
|
||||
})),
|
||||
findFirst: vi.fn(async () => ({
|
||||
id: 'episode-1',
|
||||
speakerVoices: '{}',
|
||||
})),
|
||||
update: vi.fn<(args: { data?: { speakerVoices?: string } }) => Promise<{ id: string }>>(async () => ({ id: 'episode-1' })),
|
||||
},
|
||||
}))
|
||||
|
||||
const resolveStorageKeyFromMediaValueMock = vi.hoisted(() => vi.fn(async (input: string) => {
|
||||
if (input.includes('fal')) return 'voice/storage/fal.wav'
|
||||
if (input.includes('preview')) return 'voice/storage/preview.wav'
|
||||
return null
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/api-auth', () => authMock)
|
||||
vi.mock('@/lib/prisma', () => ({ prisma: prismaMock }))
|
||||
vi.mock('@/lib/media/service', () => ({
|
||||
resolveStorageKeyFromMediaValue: resolveStorageKeyFromMediaValueMock,
|
||||
}))
|
||||
|
||||
describe('api specific - speaker voice provider contract', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('returns INVALID_PARAMS when provider is missing in PATCH payload', async () => {
|
||||
const mod = await import('@/app/api/novel-promotion/[projectId]/speaker-voice/route')
|
||||
const req = buildMockRequest({
|
||||
path: '/api/novel-promotion/project-1/speaker-voice',
|
||||
method: 'PATCH',
|
||||
body: {
|
||||
episodeId: 'episode-1',
|
||||
speaker: 'Narrator',
|
||||
voiceType: 'uploaded',
|
||||
audioUrl: '/m/fal-reference',
|
||||
},
|
||||
})
|
||||
|
||||
const res = await mod.PATCH(req, { params: Promise.resolve({ projectId: 'project-1' }) })
|
||||
const body = await res.json()
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
expect(body.error.code).toBe('INVALID_PARAMS')
|
||||
expect(prismaMock.novelPromotionEpisode.update).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('stores fal speaker voice with explicit provider and normalized audio storage key', async () => {
|
||||
const mod = await import('@/app/api/novel-promotion/[projectId]/speaker-voice/route')
|
||||
const req = buildMockRequest({
|
||||
path: '/api/novel-promotion/project-1/speaker-voice',
|
||||
method: 'PATCH',
|
||||
body: {
|
||||
episodeId: 'episode-1',
|
||||
speaker: 'Narrator',
|
||||
provider: 'fal',
|
||||
voiceType: 'uploaded',
|
||||
audioUrl: '/m/fal-reference',
|
||||
},
|
||||
})
|
||||
|
||||
const res = await mod.PATCH(req, { params: Promise.resolve({ projectId: 'project-1' }) })
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
const updateCall = prismaMock.novelPromotionEpisode.update.mock.calls[0] as
|
||||
| [{ data?: { speakerVoices?: string } }]
|
||||
| undefined
|
||||
expect(updateCall).toBeTruthy()
|
||||
if (!updateCall) throw new Error('expected update call')
|
||||
const updateArg = updateCall[0]
|
||||
const saved = JSON.parse(updateArg.data?.speakerVoices || '{}') as Record<string, unknown>
|
||||
|
||||
expect(resolveStorageKeyFromMediaValueMock).toHaveBeenCalledWith('/m/fal-reference')
|
||||
expect(saved.Narrator).toEqual({
|
||||
provider: 'fal',
|
||||
voiceType: 'uploaded',
|
||||
audioUrl: 'voice/storage/fal.wav',
|
||||
})
|
||||
})
|
||||
|
||||
it('stores bailian speaker voice with explicit provider and voiceId', async () => {
|
||||
const mod = await import('@/app/api/novel-promotion/[projectId]/speaker-voice/route')
|
||||
const req = buildMockRequest({
|
||||
path: '/api/novel-promotion/project-1/speaker-voice',
|
||||
method: 'PATCH',
|
||||
body: {
|
||||
episodeId: 'episode-1',
|
||||
speaker: 'Narrator',
|
||||
provider: 'bailian',
|
||||
voiceType: 'qwen-designed',
|
||||
voiceId: 'qwen-tts-vd-001',
|
||||
previewAudioUrl: '/m/preview-audio',
|
||||
},
|
||||
})
|
||||
|
||||
const res = await mod.PATCH(req, { params: Promise.resolve({ projectId: 'project-1' }) })
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
const updateCall = prismaMock.novelPromotionEpisode.update.mock.calls[0] as
|
||||
| [{ data?: { speakerVoices?: string } }]
|
||||
| undefined
|
||||
expect(updateCall).toBeTruthy()
|
||||
if (!updateCall) throw new Error('expected update call')
|
||||
const updateArg = updateCall[0]
|
||||
const saved = JSON.parse(updateArg.data?.speakerVoices || '{}') as Record<string, unknown>
|
||||
|
||||
expect(resolveStorageKeyFromMediaValueMock).toHaveBeenCalledWith('/m/preview-audio')
|
||||
expect(saved.Narrator).toEqual({
|
||||
provider: 'bailian',
|
||||
voiceType: 'qwen-designed',
|
||||
voiceId: 'qwen-tts-vd-001',
|
||||
previewAudioUrl: 'voice/storage/preview.wav',
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,94 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { buildMockRequest } from '../../../helpers/request'
|
||||
import {
|
||||
installAuthMocks,
|
||||
mockAuthenticated,
|
||||
resetAuthMockState,
|
||||
} from '../../../helpers/auth'
|
||||
|
||||
const probeModelLlmProtocolMock = vi.hoisted(() =>
|
||||
vi.fn(async () => ({
|
||||
success: true,
|
||||
protocol: 'responses' as const,
|
||||
checkedAt: '2026-03-05T00:00:00.000Z',
|
||||
traces: [],
|
||||
})),
|
||||
)
|
||||
|
||||
vi.mock('@/lib/user-api/model-llm-protocol-probe', () => ({
|
||||
probeModelLlmProtocol: probeModelLlmProtocolMock,
|
||||
}))
|
||||
|
||||
describe('api specific - user api-config probe model llm protocol', () => {
|
||||
const routeContext = { params: Promise.resolve({}) }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetModules()
|
||||
vi.clearAllMocks()
|
||||
resetAuthMockState()
|
||||
})
|
||||
|
||||
it('probes protocol for openai-compatible provider/model', async () => {
|
||||
installAuthMocks()
|
||||
mockAuthenticated('user-1')
|
||||
const route = await import('@/app/api/user/api-config/probe-model-llm-protocol/route')
|
||||
|
||||
const req = buildMockRequest({
|
||||
path: '/api/user/api-config/probe-model-llm-protocol',
|
||||
method: 'POST',
|
||||
body: {
|
||||
providerId: 'openai-compatible:node-1',
|
||||
modelId: 'gpt-4.1-mini',
|
||||
},
|
||||
})
|
||||
|
||||
const res = await route.POST(req, routeContext)
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json() as { success: boolean; protocol?: string }
|
||||
expect(body.success).toBe(true)
|
||||
expect(body.protocol).toBe('responses')
|
||||
expect(probeModelLlmProtocolMock).toHaveBeenCalledWith({
|
||||
userId: 'user-1',
|
||||
providerId: 'openai-compatible:node-1',
|
||||
modelId: 'gpt-4.1-mini',
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects non-openai-compatible provider ids', async () => {
|
||||
installAuthMocks()
|
||||
mockAuthenticated('user-1')
|
||||
const route = await import('@/app/api/user/api-config/probe-model-llm-protocol/route')
|
||||
|
||||
const req = buildMockRequest({
|
||||
path: '/api/user/api-config/probe-model-llm-protocol',
|
||||
method: 'POST',
|
||||
body: {
|
||||
providerId: 'gemini-compatible:node-1',
|
||||
modelId: 'gemini-3-pro-preview',
|
||||
},
|
||||
})
|
||||
|
||||
const res = await route.POST(req, routeContext)
|
||||
expect(res.status).toBe(400)
|
||||
expect(probeModelLlmProtocolMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects invalid body payload', async () => {
|
||||
installAuthMocks()
|
||||
mockAuthenticated('user-1')
|
||||
const route = await import('@/app/api/user/api-config/probe-model-llm-protocol/route')
|
||||
|
||||
const req = buildMockRequest({
|
||||
path: '/api/user/api-config/probe-model-llm-protocol',
|
||||
method: 'POST',
|
||||
body: {
|
||||
providerId: 'openai-compatible:node-1',
|
||||
modelId: '',
|
||||
},
|
||||
})
|
||||
|
||||
const res = await route.POST(req, routeContext)
|
||||
expect(res.status).toBe(400)
|
||||
expect(probeModelLlmProtocolMock).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
1298
tests/integration/api/specific/user-api-config-put.test.ts
Normal file
1298
tests/integration/api/specific/user-api-config-put.test.ts
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,123 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { buildMockRequest } from '../../../helpers/request'
|
||||
import {
|
||||
installAuthMocks,
|
||||
mockAuthenticated,
|
||||
resetAuthMockState,
|
||||
} from '../../../helpers/auth'
|
||||
|
||||
const createAssistantChatResponseMock = vi.hoisted(() =>
|
||||
vi.fn(async () => new Response('event: done\ndata: ok\n\n', {
|
||||
status: 200,
|
||||
headers: {
|
||||
'content-type': 'text/event-stream; charset=utf-8',
|
||||
},
|
||||
})),
|
||||
)
|
||||
|
||||
vi.mock('@/lib/assistant-platform', async () => {
|
||||
const actual = await vi.importActual<typeof import('@/lib/assistant-platform')>('@/lib/assistant-platform')
|
||||
return {
|
||||
...actual,
|
||||
createAssistantChatResponse: createAssistantChatResponseMock,
|
||||
}
|
||||
})
|
||||
|
||||
describe('api specific - user assistant chat', () => {
|
||||
const routeContext = { params: Promise.resolve({}) }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetModules()
|
||||
vi.clearAllMocks()
|
||||
resetAuthMockState()
|
||||
})
|
||||
|
||||
it('accepts api-config-template assistant request and forwards payload', async () => {
|
||||
installAuthMocks()
|
||||
mockAuthenticated('user-1')
|
||||
const route = await import('@/app/api/user/assistant/chat/route')
|
||||
|
||||
const req = buildMockRequest({
|
||||
path: '/api/user/assistant/chat',
|
||||
method: 'POST',
|
||||
body: {
|
||||
assistantId: 'api-config-template',
|
||||
context: {
|
||||
providerId: 'openai-compatible:oa-1',
|
||||
},
|
||||
messages: [{
|
||||
id: 'm1',
|
||||
role: 'user',
|
||||
parts: [{ type: 'text', text: '请配置文生视频模板' }],
|
||||
}],
|
||||
},
|
||||
})
|
||||
|
||||
const res = await route.POST(req, routeContext)
|
||||
expect(res.status).toBe(200)
|
||||
expect(createAssistantChatResponseMock).toHaveBeenCalledWith({
|
||||
userId: 'user-1',
|
||||
assistantId: 'api-config-template',
|
||||
context: {
|
||||
providerId: 'openai-compatible:oa-1',
|
||||
},
|
||||
messages: [{
|
||||
id: 'm1',
|
||||
role: 'user',
|
||||
parts: [{ type: 'text', text: '请配置文生视频模板' }],
|
||||
}],
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects invalid assistantId', async () => {
|
||||
installAuthMocks()
|
||||
mockAuthenticated('user-1')
|
||||
const route = await import('@/app/api/user/assistant/chat/route')
|
||||
|
||||
const req = buildMockRequest({
|
||||
path: '/api/user/assistant/chat',
|
||||
method: 'POST',
|
||||
body: {
|
||||
assistantId: 'unknown-assistant',
|
||||
messages: [],
|
||||
},
|
||||
})
|
||||
|
||||
const res = await route.POST(req, routeContext)
|
||||
expect(res.status).toBe(400)
|
||||
expect(createAssistantChatResponseMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('maps assistant platform missing-config error to 400 response', async () => {
|
||||
installAuthMocks()
|
||||
mockAuthenticated('user-1')
|
||||
const { AssistantPlatformError } = await import('@/lib/assistant-platform')
|
||||
createAssistantChatResponseMock.mockRejectedValueOnce(
|
||||
new AssistantPlatformError('ASSISTANT_MODEL_NOT_CONFIGURED', 'analysisModel is required'),
|
||||
)
|
||||
const route = await import('@/app/api/user/assistant/chat/route')
|
||||
|
||||
const req = buildMockRequest({
|
||||
path: '/api/user/assistant/chat',
|
||||
method: 'POST',
|
||||
body: {
|
||||
assistantId: 'api-config-template',
|
||||
context: {
|
||||
providerId: 'openai-compatible:oa-1',
|
||||
},
|
||||
messages: [{
|
||||
id: 'm1',
|
||||
role: 'user',
|
||||
parts: [{ type: 'text', text: 'hello' }],
|
||||
}],
|
||||
},
|
||||
})
|
||||
|
||||
const res = await route.POST(req, routeContext)
|
||||
expect(res.status).toBe(400)
|
||||
const payload = await res.json() as { code?: string; error?: { code?: string; details?: { code?: string } } }
|
||||
expect(payload.error?.code).toBe('MISSING_CONFIG')
|
||||
expect(payload.code).toBe('ASSISTANT_MODEL_NOT_CONFIGURED')
|
||||
expect(payload.error?.details?.code).toBe('ASSISTANT_MODEL_NOT_CONFIGURED')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,71 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { buildMockRequest } from '../../../helpers/request'
|
||||
|
||||
const authMock = vi.hoisted(() => ({
|
||||
requireUserAuth: vi.fn(async () => ({
|
||||
session: { user: { id: 'user-1' } },
|
||||
})),
|
||||
isErrorResponse: vi.fn((value: unknown) => value instanceof Response),
|
||||
}))
|
||||
|
||||
const prismaMock = vi.hoisted(() => ({
|
||||
userPreference: {
|
||||
findUnique: vi.fn(async () => ({
|
||||
customModels: JSON.stringify([
|
||||
{
|
||||
modelId: 'qwen3-tts-vd-2026-01-26',
|
||||
modelKey: 'bailian::qwen3-tts-vd-2026-01-26',
|
||||
name: 'Qwen3 TTS',
|
||||
type: 'audio',
|
||||
provider: 'bailian',
|
||||
},
|
||||
{
|
||||
modelId: 'qwen-voice-design',
|
||||
modelKey: 'bailian::qwen-voice-design',
|
||||
name: 'Qwen Voice Design',
|
||||
type: 'audio',
|
||||
provider: 'bailian',
|
||||
},
|
||||
]),
|
||||
customProviders: JSON.stringify([
|
||||
{
|
||||
id: 'bailian',
|
||||
name: 'Alibaba Bailian',
|
||||
apiKey: 'k-bailian',
|
||||
},
|
||||
]),
|
||||
})),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/api-auth', () => authMock)
|
||||
vi.mock('@/lib/prisma', () => ({ prisma: prismaMock }))
|
||||
vi.mock('@/lib/model-capabilities/catalog', () => ({
|
||||
findBuiltinCapabilities: vi.fn(() => undefined),
|
||||
}))
|
||||
vi.mock('@/lib/model-pricing/catalog', () => ({
|
||||
findBuiltinPricingCatalogEntry: vi.fn(() => undefined),
|
||||
}))
|
||||
|
||||
describe('api specific - user models audio filter', () => {
|
||||
const routeContext = { params: Promise.resolve({}) }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('excludes voice design models from the audio model list', async () => {
|
||||
const mod = await import('@/app/api/user/models/route')
|
||||
const req = buildMockRequest({
|
||||
path: '/api/user/models',
|
||||
method: 'GET',
|
||||
})
|
||||
const res = await mod.GET(req, routeContext)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json() as { audio: Array<{ value: string }> }
|
||||
expect(body.audio.map((item) => item.value)).toEqual([
|
||||
'bailian::qwen3-tts-vd-2026-01-26',
|
||||
])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,61 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { buildMockRequest } from '../../../helpers/request'
|
||||
|
||||
const authMock = vi.hoisted(() => ({
|
||||
requireUserAuth: vi.fn(async () => ({
|
||||
session: { user: { id: 'user-1' } },
|
||||
})),
|
||||
isErrorResponse: vi.fn((value: unknown) => value instanceof Response),
|
||||
}))
|
||||
|
||||
const prismaMock = vi.hoisted(() => ({
|
||||
userPreference: {
|
||||
upsert: vi.fn(async () => ({
|
||||
userId: 'user-1',
|
||||
artStyle: 'realistic',
|
||||
})),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/api-auth', () => authMock)
|
||||
vi.mock('@/lib/prisma', () => ({ prisma: prismaMock }))
|
||||
|
||||
describe('api specific - user preference art style validation', () => {
|
||||
const routeContext = { params: Promise.resolve({}) }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('accepts valid artStyle and persists normalized value', async () => {
|
||||
const mod = await import('@/app/api/user-preference/route')
|
||||
const req = buildMockRequest({
|
||||
path: '/api/user-preference',
|
||||
method: 'PATCH',
|
||||
body: { artStyle: ' realistic ' },
|
||||
})
|
||||
|
||||
const res = await mod.PATCH(req, routeContext)
|
||||
expect(res.status).toBe(200)
|
||||
expect(prismaMock.userPreference.upsert).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
update: expect.objectContaining({ artStyle: 'realistic' }),
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('rejects invalid artStyle with invalid params', async () => {
|
||||
const mod = await import('@/app/api/user-preference/route')
|
||||
const req = buildMockRequest({
|
||||
path: '/api/user-preference',
|
||||
method: 'PATCH',
|
||||
body: { artStyle: 'anime' },
|
||||
})
|
||||
|
||||
const res = await mod.PATCH(req, routeContext)
|
||||
const body = await res.json()
|
||||
expect(res.status).toBe(400)
|
||||
expect(body.error.code).toBe('INVALID_PARAMS')
|
||||
expect(prismaMock.userPreference.upsert).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,181 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { buildMockRequest } from '../../../helpers/request'
|
||||
|
||||
const authMock = vi.hoisted(() => ({
|
||||
requireProjectAuthLight: vi.fn(async () => ({
|
||||
session: { user: { id: 'user-1' } },
|
||||
project: { id: 'project-1', userId: 'user-1', mode: 'novel-promotion' },
|
||||
})),
|
||||
isErrorResponse: vi.fn((value: unknown) => value instanceof Response),
|
||||
}))
|
||||
|
||||
const prismaMock = vi.hoisted(() => ({
|
||||
userPreference: {
|
||||
findUnique: vi.fn(async () => ({ audioModel: 'fal::fal-ai/index-tts-2/text-to-speech' })),
|
||||
},
|
||||
novelPromotionProject: {
|
||||
findUnique: vi.fn<() => Promise<{
|
||||
id: string
|
||||
audioModel: string | null
|
||||
characters: Array<{ name: string; customVoiceUrl: string; voiceId: string | null }>
|
||||
} | null>>(async () => ({
|
||||
id: 'np-1',
|
||||
audioModel: 'fal::project-tts-model',
|
||||
characters: [
|
||||
{ name: 'Narrator', customVoiceUrl: 'https://voice.example/narrator.wav', voiceId: null },
|
||||
],
|
||||
})),
|
||||
},
|
||||
novelPromotionEpisode: {
|
||||
findFirst: vi.fn(async () => ({
|
||||
id: 'episode-1',
|
||||
speakerVoices: '{}',
|
||||
})),
|
||||
},
|
||||
novelPromotionVoiceLine: {
|
||||
findFirst: vi.fn(async () => ({
|
||||
id: 'line-1',
|
||||
speaker: 'Narrator',
|
||||
content: 'hello world',
|
||||
})),
|
||||
findMany: vi.fn(async () => []),
|
||||
},
|
||||
}))
|
||||
|
||||
const submitTaskMock = vi.hoisted(() => vi.fn<typeof import('@/lib/task/submitter').submitTask>(async () => ({
|
||||
success: true,
|
||||
async: true,
|
||||
taskId: 'task-1',
|
||||
runId: null,
|
||||
status: 'queued',
|
||||
deduped: false,
|
||||
})))
|
||||
|
||||
const apiConfigMock = vi.hoisted(() => ({
|
||||
resolveModelSelectionOrSingle: vi.fn(async (_userId: string, model: string | null | undefined) => ({
|
||||
provider: 'fal',
|
||||
modelId: 'fal-ai/index-tts-2/text-to-speech',
|
||||
modelKey: model || 'fal::fal-ai/index-tts-2/text-to-speech',
|
||||
mediaType: 'audio',
|
||||
})),
|
||||
getProviderKey: vi.fn((providerId: string) => providerId),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/api-auth', () => authMock)
|
||||
vi.mock('@/lib/prisma', () => ({ prisma: prismaMock }))
|
||||
vi.mock('@/lib/task/submitter', () => ({ submitTask: submitTaskMock }))
|
||||
vi.mock('@/lib/api-config', () => apiConfigMock)
|
||||
vi.mock('@/lib/task/resolve-locale', () => ({
|
||||
resolveRequiredTaskLocale: vi.fn(() => 'zh'),
|
||||
}))
|
||||
vi.mock('@/lib/billing', () => ({
|
||||
buildDefaultTaskBillingInfo: vi.fn(() => ({ mode: 'default' })),
|
||||
}))
|
||||
vi.mock('@/lib/task/has-output', () => ({
|
||||
hasVoiceLineAudioOutput: vi.fn(async () => false),
|
||||
}))
|
||||
|
||||
describe('api specific - voice generate default audio model', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('uses project audioModel when request does not provide one', async () => {
|
||||
const mod = await import('@/app/api/novel-promotion/[projectId]/voice-generate/route')
|
||||
const req = buildMockRequest({
|
||||
path: '/api/novel-promotion/project-1/voice-generate',
|
||||
method: 'POST',
|
||||
body: {
|
||||
episodeId: 'episode-1',
|
||||
lineId: 'line-1',
|
||||
},
|
||||
})
|
||||
|
||||
const res = await mod.POST(req, { params: Promise.resolve({ projectId: 'project-1' }) })
|
||||
expect(res.status).toBe(200)
|
||||
expect(apiConfigMock.resolveModelSelectionOrSingle).toHaveBeenCalledWith(
|
||||
'user-1',
|
||||
'fal::project-tts-model',
|
||||
'audio',
|
||||
)
|
||||
|
||||
const submitCall = submitTaskMock.mock.calls[0] as [{ payload?: Record<string, unknown> }] | undefined
|
||||
const submitArg = submitCall?.[0]
|
||||
expect(submitArg?.payload?.audioModel).toBe('fal::project-tts-model')
|
||||
})
|
||||
|
||||
it('request audioModel overrides user preference audioModel', async () => {
|
||||
const mod = await import('@/app/api/novel-promotion/[projectId]/voice-generate/route')
|
||||
const req = buildMockRequest({
|
||||
path: '/api/novel-promotion/project-1/voice-generate',
|
||||
method: 'POST',
|
||||
body: {
|
||||
episodeId: 'episode-1',
|
||||
lineId: 'line-1',
|
||||
audioModel: 'fal::custom-tts',
|
||||
},
|
||||
})
|
||||
|
||||
const res = await mod.POST(req, { params: Promise.resolve({ projectId: 'project-1' }) })
|
||||
expect(res.status).toBe(200)
|
||||
expect(apiConfigMock.resolveModelSelectionOrSingle).toHaveBeenCalledWith(
|
||||
'user-1',
|
||||
'fal::custom-tts',
|
||||
'audio',
|
||||
)
|
||||
})
|
||||
|
||||
it('falls back to user preference audioModel when project audioModel is empty', async () => {
|
||||
prismaMock.novelPromotionProject.findUnique.mockResolvedValueOnce({
|
||||
id: 'np-1',
|
||||
audioModel: null,
|
||||
characters: [
|
||||
{ name: 'Narrator', customVoiceUrl: 'https://voice.example/narrator.wav', voiceId: null },
|
||||
],
|
||||
})
|
||||
|
||||
const mod = await import('@/app/api/novel-promotion/[projectId]/voice-generate/route')
|
||||
const req = buildMockRequest({
|
||||
path: '/api/novel-promotion/project-1/voice-generate',
|
||||
method: 'POST',
|
||||
body: {
|
||||
episodeId: 'episode-1',
|
||||
lineId: 'line-1',
|
||||
},
|
||||
})
|
||||
|
||||
const res = await mod.POST(req, { params: Promise.resolve({ projectId: 'project-1' }) })
|
||||
expect(res.status).toBe(200)
|
||||
expect(apiConfigMock.resolveModelSelectionOrSingle).toHaveBeenCalledWith(
|
||||
'user-1',
|
||||
'fal::fal-ai/index-tts-2/text-to-speech',
|
||||
'audio',
|
||||
)
|
||||
})
|
||||
|
||||
it('returns an explicit qwen voiceId error when only uploaded reference audio is available', async () => {
|
||||
apiConfigMock.resolveModelSelectionOrSingle.mockResolvedValueOnce({
|
||||
provider: 'bailian',
|
||||
modelId: 'qwen3-tts-vd-2026-01-26',
|
||||
modelKey: 'bailian::qwen3-tts-vd-2026-01-26',
|
||||
mediaType: 'audio',
|
||||
})
|
||||
|
||||
const mod = await import('@/app/api/novel-promotion/[projectId]/voice-generate/route')
|
||||
const req = buildMockRequest({
|
||||
path: '/api/novel-promotion/project-1/voice-generate',
|
||||
method: 'POST',
|
||||
body: {
|
||||
episodeId: 'episode-1',
|
||||
lineId: 'line-1',
|
||||
},
|
||||
})
|
||||
|
||||
const res = await mod.POST(req, { params: Promise.resolve({ projectId: 'project-1' }) })
|
||||
expect(res.status).toBe(400)
|
||||
|
||||
const json = await res.json()
|
||||
expect(json.error?.message).toBe('无音色ID,QwenTTS 必须使用 AI 设计音色')
|
||||
expect(submitTaskMock).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user