mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-12-03 06:24:30 +00:00
test(agent): write solid tests for agent workflows and activities
This commit is contained in:
@@ -1,6 +1,33 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { generateEmbeddingActivity } from './ai'
|
||||
import {
|
||||
generateEmbeddingActivity,
|
||||
generateTextEmbeddingActivity,
|
||||
extractAiMetadataActivity,
|
||||
getEmbeddingContextActivity,
|
||||
saveAssetEmbeddingsActivity,
|
||||
} from './ai'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { transcodeService } from '@shumai/transcode'
|
||||
import { prisma, AssetType, AssetStatus } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import * as fs from 'fs'
|
||||
|
||||
vi.mock('fs', async (importOriginal) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- importOriginal returns the raw fs module, typed dynamically as any here
|
||||
const actual = await importOriginal<any>()
|
||||
const mockRead = vi.fn((path, options) => {
|
||||
if (typeof path === 'string' && (path.includes('video-chunk') || path.includes('out1.webp'))) {
|
||||
return Buffer.from('chunk-data')
|
||||
}
|
||||
return actual.readFileSync(path, options)
|
||||
})
|
||||
return {
|
||||
...actual,
|
||||
writeFileSync: vi.fn(),
|
||||
readFileSync: mockRead,
|
||||
unlinkSync: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@shumai/core/src/s3/s3', () => ({
|
||||
s3Service: {
|
||||
@@ -11,6 +38,30 @@ vi.mock('@shumai/core/src/s3/s3', () => ({
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/transcode', () => ({
|
||||
transcodeService: {
|
||||
extractVideoFrames: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('child_process', () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock functions dynamically return varying types based on test command calls
|
||||
const execMock: any = vi.fn((cmd: any, cb: any) => {
|
||||
cb(null, '120.0\n', '')
|
||||
})
|
||||
// Setup custom promisify behavior to return { stdout, stderr }
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock functions dynamically return varying types based on test command calls
|
||||
execMock[Symbol.for('nodejs.util.promisify.custom')] = vi.fn(async (cmd: any) => {
|
||||
if (cmd.includes('ffprobe')) {
|
||||
return { stdout: '120.0\n', stderr: '' }
|
||||
}
|
||||
return { stdout: '', stderr: '' }
|
||||
})
|
||||
return {
|
||||
exec: execMock,
|
||||
}
|
||||
})
|
||||
|
||||
const mockEmbedContent = vi.fn().mockResolvedValue({
|
||||
embeddings: [
|
||||
{
|
||||
@@ -21,7 +72,7 @@ const mockEmbedContent = vi.fn().mockResolvedValue({
|
||||
|
||||
vi.mock('@google/genai', () => {
|
||||
return {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention -- matches external library GoogleGenAI export naming convention
|
||||
GoogleGenAI: class {
|
||||
models = {
|
||||
embedContent: mockEmbedContent,
|
||||
@@ -30,7 +81,7 @@ vi.mock('@google/genai', () => {
|
||||
}
|
||||
})
|
||||
|
||||
describe('AI Activities', () => {
|
||||
describe('AI Activities Unit Tests', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
process.env.GEMINI_API_KEY = 'test-key'
|
||||
@@ -40,8 +91,7 @@ describe('AI Activities', () => {
|
||||
vi.mocked(s3Service.getObject).mockResolvedValue({
|
||||
buffer: Buffer.from('test-image'),
|
||||
contentType: 'image/png',
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock getObject return value needs broad any casting
|
||||
} as any)
|
||||
} as unknown as { buffer: Buffer; contentType: string })
|
||||
|
||||
const context = {
|
||||
agent: { config: { provider: 'google', model: 'gemini' } },
|
||||
@@ -58,4 +108,222 @@ describe('AI Activities', () => {
|
||||
expect(res.embeddings[0].embedding).toEqual([0.1, 0.2, 0.3])
|
||||
expect(s3Service.getObject).toHaveBeenCalledWith('shumai', 'test.png')
|
||||
})
|
||||
|
||||
it('should generate video embedding in chunks', async () => {
|
||||
vi.mocked(s3Service.getObject).mockResolvedValue({
|
||||
buffer: Buffer.from('test-video'),
|
||||
contentType: 'video/mp4',
|
||||
} as unknown as { buffer: Buffer; contentType: string })
|
||||
|
||||
const context = {
|
||||
agent: { config: { provider: 'google', model: 'gemini' } },
|
||||
asset: { id: 'a2', mediaType: 'video/mp4', storageKey: { key: 'test.mp4' } },
|
||||
}
|
||||
|
||||
const res = await generateEmbeddingActivity({
|
||||
teamId: 't1',
|
||||
assetId: 'a2',
|
||||
context,
|
||||
})
|
||||
|
||||
// Duration is 120s, chunks are 60s, so it should generate 2 chunks (0-60, 60-120)
|
||||
expect(res.embeddings.length).toBe(2)
|
||||
expect(res.embeddings[0]).toEqual({ embedding: [0.1, 0.2, 0.3], startTime: 0, endTime: 60 })
|
||||
expect(res.embeddings[1]).toEqual({ embedding: [0.1, 0.2, 0.3], startTime: 60, endTime: 120 })
|
||||
|
||||
expect(vi.mocked(fs.writeFileSync)).toHaveBeenCalled()
|
||||
expect(vi.mocked(fs.readFileSync)).toHaveBeenCalled()
|
||||
expect(vi.mocked(fs.unlinkSync)).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should generate text embedding successfully', async () => {
|
||||
const res = await generateTextEmbeddingActivity({
|
||||
text: 'Search query',
|
||||
teamId: 't1',
|
||||
})
|
||||
|
||||
expect(res.embedding).toEqual([0.1, 0.2, 0.3])
|
||||
expect(mockEmbedContent).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
model: 'gemini-embedding-2',
|
||||
contents: [
|
||||
expect.objectContaining({
|
||||
parts: [{ text: 'Search query' }],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
describe('extractAiMetadataActivity', () => {
|
||||
it('should return existing images if they are already in S3 storage', async () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock returned object cast as any due to partial implementation
|
||||
vi.mocked(s3Service.headObject).mockResolvedValue({} as any)
|
||||
vi.mocked(s3Service.listObjects).mockResolvedValue([
|
||||
'project/ai_metadata/1.webp',
|
||||
'project/ai_metadata/2.webp',
|
||||
])
|
||||
|
||||
const res = await extractAiMetadataActivity({
|
||||
assetKey: 'project/video.mp4',
|
||||
filePath: '/tmp/video.mp4',
|
||||
type: 'autofill',
|
||||
isImage: false,
|
||||
})
|
||||
|
||||
expect(res).toEqual(['project/ai_metadata/1.webp', 'project/ai_metadata/2.webp'])
|
||||
expect(s3Service.headObject).toHaveBeenCalledWith('shumai', 'project/ai_metadata/1.webp')
|
||||
expect(transcodeService.extractVideoFrames).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should extract frames and upload to S3 if not already present', async () => {
|
||||
vi.mocked(s3Service.headObject).mockRejectedValue(new Error('Not Found'))
|
||||
vi.mocked(transcodeService.extractVideoFrames).mockResolvedValue(['/tmp/out1.webp'])
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock returned object cast as any due to partial implementation
|
||||
vi.mocked(s3Service.putObject).mockResolvedValue({} as any)
|
||||
|
||||
const res = await extractAiMetadataActivity({
|
||||
assetKey: 'project/video.mp4',
|
||||
filePath: '/tmp/video.mp4',
|
||||
type: 'autofill',
|
||||
isImage: false,
|
||||
})
|
||||
|
||||
expect(res).toEqual(['project/ai_metadata/out1.webp'])
|
||||
expect(transcodeService.extractVideoFrames).toHaveBeenCalledWith({
|
||||
inputFile: '/tmp/video.mp4',
|
||||
outputDir: '/tmp',
|
||||
numFrames: 30,
|
||||
frameHeight: 720,
|
||||
isImage: false,
|
||||
})
|
||||
expect(s3Service.putObject).toHaveBeenCalledWith(
|
||||
'shumai',
|
||||
'project/ai_metadata/out1.webp',
|
||||
expect.any(Buffer),
|
||||
expect.any(Number),
|
||||
'image/webp',
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('AI Database Activities Integration', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- variables hold Prisma model output types that are difficult to type explicitly in tests
|
||||
let team: any
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- variables hold Prisma model output types that are difficult to type explicitly in tests
|
||||
let user: any
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- variables hold Prisma model output types that are difficult to type explicitly in tests
|
||||
let asset: any
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- variables hold Prisma model output types that are difficult to type explicitly in tests
|
||||
let storageKey: any
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.restoreAllMocks()
|
||||
|
||||
team = await prisma.team.create({
|
||||
data: { name: 'AI Team' },
|
||||
})
|
||||
|
||||
user = await prisma.user.create({
|
||||
data: {
|
||||
name: 'AI Agent User',
|
||||
email: 'aiagent@shumai.ai',
|
||||
type: 'agent',
|
||||
},
|
||||
})
|
||||
|
||||
// Add user as a member of the team
|
||||
await prisma.teamMember.create({
|
||||
data: {
|
||||
teamId: team.id,
|
||||
userId: user.id,
|
||||
role: 'editor',
|
||||
},
|
||||
})
|
||||
|
||||
storageKey = await prisma.storageKey.create({
|
||||
data: {
|
||||
key: 'media/video.mp4',
|
||||
},
|
||||
})
|
||||
|
||||
asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'video.mp4',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.uploaded,
|
||||
mediaType: 'video/mp4',
|
||||
storageKeyId: storageKey.id,
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
describe('getEmbeddingContextActivity', () => {
|
||||
it('should retrieve embedding context and throw if embedding agent not configured/enabled', async () => {
|
||||
// Expect throw since agent not created yet
|
||||
await expect(
|
||||
getEmbeddingContextActivity({ teamId: team.id, assetId: asset.id }),
|
||||
).rejects.toThrow('embedding feature is disabled or agent not found')
|
||||
|
||||
// Create embedding agent
|
||||
await prisma.agent.create({
|
||||
data: {
|
||||
id: user.id, // match user.id
|
||||
teamId: team.id,
|
||||
type: 'embedding',
|
||||
enabled: true,
|
||||
config: {
|
||||
provider: 'openai',
|
||||
model: 'gpt-4',
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const ctx = await getEmbeddingContextActivity({
|
||||
teamId: team.id,
|
||||
assetId: asset.id,
|
||||
})
|
||||
|
||||
expect(ctx.agent.id).toBe(user.id)
|
||||
expect(ctx.asset.id).toBe(asset.id)
|
||||
expect(ctx.asset.mediaType).toBe('video/mp4')
|
||||
})
|
||||
})
|
||||
|
||||
describe('saveAssetEmbeddingsActivity', () => {
|
||||
it('should save embeddings with start and end times to the database', async () => {
|
||||
const embeddings = [
|
||||
{
|
||||
embedding: Array(1536).fill(0.01),
|
||||
startTime: 0.0,
|
||||
endTime: 60.0,
|
||||
},
|
||||
{
|
||||
embedding: Array(1536).fill(0.02),
|
||||
},
|
||||
]
|
||||
|
||||
await saveAssetEmbeddingsActivity({
|
||||
assetId: asset.id,
|
||||
embeddings,
|
||||
})
|
||||
|
||||
// Query raw embeddings from DB
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- db query output is a raw postgres result array typed as any
|
||||
const dbEmbeddings: any[] = await prisma.$queryRaw`
|
||||
SELECT id, asset_id as "assetId", start_time as "startTime", end_time as "endTime"
|
||||
FROM asset_embeddings
|
||||
WHERE asset_id = ${asset.id}
|
||||
ORDER BY start_time ASC NULLS LAST
|
||||
`
|
||||
|
||||
expect(dbEmbeddings.length).toBe(2)
|
||||
expect(dbEmbeddings[0].startTime).toBe(0.0)
|
||||
expect(dbEmbeddings[0].endTime).toBe(60.0)
|
||||
expect(dbEmbeddings[1].startTime).toBeNull()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user