Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✅ test: add unit tests for video generation feature

YuTengjing335e246ac5fe
diff --git a/packages/model-bank/src/standard-parameters/video.test.ts b/packages/model-bank/src/standard-parameters/video.test.ts
new file mode 100644
index 00000000000..cc7cd73889f
--- /dev/null
+++ b/packages/model-bank/src/standard-parameters/video.test.ts
@@ -0,0 +1,178 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ extractVideoDefaultValues,
+ MAX_VIDEO_SEED,
+ PRESET_VIDEO_ASPECT_RATIOS,
+ PRESET_VIDEO_RESOLUTIONS,
+ type RuntimeVideoGenParams,
+ validateVideoModelParamsSchema,
+ VideoModelParamsMetaSchema,
+ type VideoModelParamsSchema,
+} from './video';
+
+describe('video standard-parameters', () => {
+ describe('VideoModelParamsMetaSchema', () => {
+ it('should validate a complete schema', () => {
+ const fullSchema: VideoModelParamsSchema = {
+ aspectRatio: { default: '16:9', enum: ['16:9', '9:16', '1:1'] },
+ cameraFixed: { default: false },
+ duration: { default: 5, max: 10, min: 1, step: 1 },
+ endImageUrl: { default: null },
+ generateAudio: { default: true },
+ imageUrl: { default: null },
+ prompt: { default: '' },
+ resolution: { default: '720p', enum: ['480p', '720p', '1080p'] },
+ seed: { default: null },
+ };
+
+ expect(() => VideoModelParamsMetaSchema.parse(fullSchema)).not.toThrow();
+ });
+
+ it('should validate minimal schema with only prompt', () => {
+ const minimalSchema: VideoModelParamsSchema = {
+ prompt: { default: '' },
+ };
+
+ expect(() => VideoModelParamsMetaSchema.parse(minimalSchema)).not.toThrow();
+ });
+
+ it('should apply default values correctly', () => {
+ const schema: VideoModelParamsSchema = {
+ cameraFixed: {},
+ generateAudio: {},
+ prompt: {},
+ seed: {},
+ };
+
+ const result = VideoModelParamsMetaSchema.parse(schema);
+
+ expect(result.prompt.default).toBe('');
+ expect(result.cameraFixed?.default).toBe(false);
+ expect(result.generateAudio?.default).toBe(true);
+ expect(result.seed?.default).toBeNull();
+ expect(result.seed?.max).toBe(MAX_VIDEO_SEED);
+ expect(result.seed?.min).toBe(-1);
+ });
+
+ it('should reject invalid types', () => {
+ const invalidSchema = {
+ prompt: { default: 123 }, // Should be string
+ };
+
+ expect(() => VideoModelParamsMetaSchema.parse(invalidSchema)).toThrow();
+ });
+ });
+
+ describe('validateVideoModelParamsSchema', () => {
+ it('should validate correct schema', () => {
+ const schema: VideoModelParamsSchema = {
+ prompt: { default: 'test' },
+ };
+
+ expect(() => validateVideoModelParamsSchema(schema)).not.toThrow();
+ });
+
+ it('should throw for invalid schema', () => {
+ const invalidSchema = {
+ prompt: { default: 42 },
+ };
+
+ expect(() => validateVideoModelParamsSchema(invalidSchema)).toThrow();
+ });
+ });
+
+ describe('extractVideoDefaultValues', () => {
+ it('should extract all default values from complete schema', () => {
+ const schema: VideoModelParamsSchema = {
+ aspectRatio: { default: '16:9', enum: ['16:9', '9:16'] },
+ cameraFixed: { default: true },
+ duration: { default: 5, max: 10, min: 1 },
+ generateAudio: { default: false },
+ prompt: { default: 'test prompt' },
+ resolution: { default: '1080p', enum: ['720p', '1080p'] },
+ seed: { default: 42 },
+ };
+
+ const result = extractVideoDefaultValues(schema);
+
+ expect(result.prompt).toBe('test prompt');
+ expect(result.aspectRatio).toBe('16:9');
+ expect(result.cameraFixed).toBe(true);
+ expect(result.duration).toBe(5);
+ expect(result.generateAudio).toBe(false);
+ expect(result.resolution).toBe('1080p');
+ expect(result.seed).toBe(42);
+ });
+
+ it('should extract defaults from minimal schema', () => {
+ const schema: VideoModelParamsSchema = {
+ prompt: {},
+ };
+
+ const result = extractVideoDefaultValues(schema);
+
+ expect(result.prompt).toBe('');
+ });
+
+ it('should extract null defaults for imageUrl and endImageUrl', () => {
+ const schema: VideoModelParamsSchema = {
+ endImageUrl: { default: null },
+ imageUrl: { default: null },
+ prompt: { default: 'test' },
+ };
+
+ const result = extractVideoDefaultValues(schema);
+
+ expect(result.imageUrl).toBeNull();
+ expect(result.endImageUrl).toBeNull();
+ });
+
+ it('should preserve correct types for each field', () => {
+ const schema: VideoModelParamsSchema = {
+ cameraFixed: { default: false },
+ generateAudio: { default: true },
+ prompt: { default: 'hello' },
+ seed: { default: null },
+ };
+
+ const result = extractVideoDefaultValues(schema);
+
+ expect(typeof result.prompt).toBe('string');
+ expect(typeof result.cameraFixed).toBe('boolean');
+ expect(typeof result.generateAudio).toBe('boolean');
+ expect(result.seed).toBeNull();
+ });
+ });
+
+ describe('constants', () => {
+ it('MAX_VIDEO_SEED should equal 2^32 - 1', () => {
+ expect(MAX_VIDEO_SEED).toBe(4294967295);
+ });
+
+ it('PRESET_VIDEO_ASPECT_RATIOS should contain standard ratios', () => {
+ expect(PRESET_VIDEO_ASPECT_RATIOS).toContain('16:9');
+ expect(PRESET_VIDEO_ASPECT_RATIOS).toContain('9:16');
+ expect(PRESET_VIDEO_ASPECT_RATIOS).toContain('1:1');
+ });
+
+ it('PRESET_VIDEO_RESOLUTIONS should contain standard resolutions', () => {
+ expect(PRESET_VIDEO_RESOLUTIONS).toContain('480p');
+ expect(PRESET_VIDEO_RESOLUTIONS).toContain('720p');
+ expect(PRESET_VIDEO_RESOLUTIONS).toContain('1080p');
+ });
+ });
+
+ describe('type inference', () => {
+ it('RuntimeVideoGenParams should require prompt and make others optional', () => {
+ const params: RuntimeVideoGenParams = {
+ prompt: 'required prompt',
+ };
+
+ expect(params.prompt).toBe('required prompt');
+ expect(params.cameraFixed).toBeUndefined();
+ expect(params.generateAudio).toBeUndefined();
+ expect(params.seed).toBeUndefined();
+ });
+ });
+});
diff --git a/packages/model-runtime/src/core/usageConverters/utils/computeVideoCost.test.ts b/packages/model-runtime/src/core/usageConverters/utils/computeVideoCost.test.ts
new file mode 100644
index 00000000000..d039db8cb1b
--- /dev/null
+++ b/packages/model-runtime/src/core/usageConverters/utils/computeVideoCost.test.ts
@@ -0,0 +1,290 @@
+import type { Pricing } from 'model-bank';
+import { describe, expect, it } from 'vitest';
+
+import type { VideoGenerationParams } from './computeVideoCost';
+import { computeVideoCost } from './computeVideoCost';
+
+describe('computeVideoCost', () => {
+ describe('fixed pricing strategy', () => {
+ it('should compute cost with millionTokens unit', () => {
+ const pricing: Pricing = {
+ units: [
+ {
+ name: 'videoGeneration',
+ rate: 0.21,
+ strategy: 'fixed',
+ unit: 'millionTokens',
+ },
+ ],
+ };
+
+ const result = computeVideoCost(pricing, 500_000, {});
+
+ expect(result).toBeDefined();
+ expect(result?.totalCost).toBe(0.105);
+ expect(result?.totalCredits).toBe(105_000);
+ expect(result?.breakdown?.completionTokens).toBe(500_000);
+ expect(result?.breakdown?.pricePerMillionTokens).toBe(0.21);
+ });
+
+ it('should return undefined when unit is not millionTokens', () => {
+ const pricing: Pricing = {
+ units: [
+ {
+ name: 'videoGeneration',
+ rate: 0.21,
+ strategy: 'fixed',
+ unit: 'image' as any,
+ },
+ ],
+ };
+
+ const result = computeVideoCost(pricing, 500_000, {});
+
+ expect(result).toBeUndefined();
+ });
+
+ it('should handle zero tokens', () => {
+ const pricing: Pricing = {
+ units: [
+ {
+ name: 'videoGeneration',
+ rate: 0.21,
+ strategy: 'fixed',
+ unit: 'millionTokens',
+ },
+ ],
+ };
+
+ const result = computeVideoCost(pricing, 0, {});
+
+ expect(result).toBeDefined();
+ expect(result?.totalCost).toBe(0);
+ expect(result?.totalCredits).toBe(0);
+ });
+ });
+
+ describe('lookup pricing strategy', () => {
+ it('should compute lookup pricing with generateAudio param', () => {
+ const pricing: Pricing = {
+ units: [
+ {
+ lookup: {
+ pricingParams: ['generateAudio'],
+ prices: {
+ false: 0.21,
+ true: 0.42,
+ },
+ },
+ name: 'videoGeneration',
+ strategy: 'lookup',
+ unit: 'millionTokens',
+ },
+ ],
+ };
+
+ const params: VideoGenerationParams = { generateAudio: true };
+ const result = computeVideoCost(pricing, 1_000_000, params);
+
+ expect(result).toBeDefined();
+ expect(result?.totalCost).toBe(0.42);
+ expect(result?.totalCredits).toBe(420_000);
+ expect(result?.breakdown?.lookupKey).toBe('true');
+ });
+
+ it('should return undefined when lookup param is missing', () => {
+ const pricing: Pricing = {
+ units: [
+ {
+ lookup: {
+ pricingParams: ['generateAudio'],
+ prices: { true: 0.42 },
+ },
+ name: 'videoGeneration',
+ strategy: 'lookup',
+ unit: 'millionTokens',
+ },
+ ],
+ };
+
+ // generateAudio is undefined
+ const result = computeVideoCost(pricing, 1_000_000, {});
+
+ expect(result).toBeUndefined();
+ });
+
+ it('should return undefined when lookup key has no matching price', () => {
+ const pricing: Pricing = {
+ units: [
+ {
+ lookup: {
+ pricingParams: ['generateAudio'],
+ prices: { true: 0.42 },
+ },
+ name: 'videoGeneration',
+ strategy: 'lookup',
+ unit: 'millionTokens',
+ },
+ ],
+ };
+
+ const params: VideoGenerationParams = { generateAudio: false };
+ const result = computeVideoCost(pricing, 1_000_000, params);
+
+ expect(result).toBeUndefined();
+ });
+
+ it('should return undefined when no pricingParams defined', () => {
+ const pricing: Pricing = {
+ units: [
+ {
+ lookup: {
+ pricingParams: [] as any,
+ prices: { true: 0.42 },
+ } as any,
+ name: 'videoGeneration',
+ strategy: 'lookup',
+ unit: 'millionTokens',
+ },
+ ],
+ };
+
+ const result = computeVideoCost(pricing, 1_000_000, { generateAudio: true });
+
+ expect(result).toBeUndefined();
+ });
+
+ it('should return undefined when param value is null', () => {
+ const pricing: Pricing = {
+ units: [
+ {
+ lookup: {
+ pricingParams: ['generateAudio'],
+ prices: { true: 0.42 },
+ },
+ name: 'videoGeneration',
+ strategy: 'lookup',
+ unit: 'millionTokens',
+ },
+ ],
+ };
+
+ const params: VideoGenerationParams = { generateAudio: null as any };
+ const result = computeVideoCost(pricing, 1_000_000, params);
+
+ expect(result).toBeUndefined();
+ });
+ });
+
+ describe('currency conversion', () => {
+ it('should convert CNY to USD', () => {
+ const pricing: Pricing = {
+ currency: 'CNY',
+ units: [
+ {
+ name: 'videoGeneration',
+ rate: 1.5,
+ strategy: 'fixed',
+ unit: 'millionTokens',
+ },
+ ],
+ };
+
+ const result = computeVideoCost(pricing, 1_000_000, {});
+
+ expect(result).toBeDefined();
+ // 1.5 CNY / 7.12 = ~0.2107
+ expect(result?.totalCost).toBeCloseTo(1.5 / 7.12, 10);
+ });
+
+ it('should not convert when currency is USD', () => {
+ const pricing: Pricing = {
+ currency: 'USD',
+ units: [
+ {
+ name: 'videoGeneration',
+ rate: 0.21,
+ strategy: 'fixed',
+ unit: 'millionTokens',
+ },
+ ],
+ };
+
+ const result = computeVideoCost(pricing, 1_000_000, {});
+
+ expect(result?.totalCost).toBe(0.21);
+ });
+
+ it('should default to USD when currency is not specified', () => {
+ const pricing: Pricing = {
+ units: [
+ {
+ name: 'videoGeneration',
+ rate: 0.21,
+ strategy: 'fixed',
+ unit: 'millionTokens',
+ },
+ ],
+ };
+
+ const result = computeVideoCost(pricing, 1_000_000, {});
+
+ expect(result?.totalCost).toBe(0.21);
+ });
+ });
+
+ describe('edge cases', () => {
+ it('should return undefined when no videoGeneration unit found', () => {
+ const pricing: Pricing = {
+ units: [
+ {
+ name: 'textGeneration' as any,
+ rate: 0.01,
+ strategy: 'fixed',
+ unit: 'millionTokens',
+ },
+ ],
+ };
+
+ const result = computeVideoCost(pricing, 1_000_000, {});
+
+ expect(result).toBeUndefined();
+ });
+
+ it('should return undefined for unsupported pricing strategy', () => {
+ const pricing = {
+ units: [
+ {
+ name: 'videoGeneration',
+ strategy: 'unknown_strategy',
+ unit: 'millionTokens',
+ },
+ ],
+ } as unknown as Pricing;
+
+ const result = computeVideoCost(pricing, 1_000_000, {});
+
+ expect(result).toBeUndefined();
+ });
+
+ it('should apply Math.ceil on totalCredits', () => {
+ const pricing: Pricing = {
+ units: [
+ {
+ name: 'videoGeneration',
+ rate: 0.000001,
+ strategy: 'fixed',
+ unit: 'millionTokens',
+ },
+ ],
+ };
+
+ // (0.000001 * 1) / 1_000_000 = 1e-12 USD → credits = Math.ceil(1e-12 * 1_000_000) = 1
+ const result = computeVideoCost(pricing, 1, {});
+
+ expect(result).toBeDefined();
+ expect(result?.totalCredits).toBe(1);
+ expect(Number.isInteger(result?.totalCredits)).toBe(true);
+ });
+ });
+});
diff --git a/packages/model-runtime/src/core/usageConverters/utils/resolveVideoSinglePrice.test.ts b/packages/model-runtime/src/core/usageConverters/utils/resolveVideoSinglePrice.test.ts
new file mode 100644
index 00000000000..a60751364e6
--- /dev/null
+++ b/packages/model-runtime/src/core/usageConverters/utils/resolveVideoSinglePrice.test.ts
@@ -0,0 +1,50 @@
+import type { Pricing } from 'model-bank';
+import { describe, expect, it } from 'vitest';
+
+import { resolveVideoSinglePrice } from './resolveVideoSinglePrice';
+
+describe('resolveVideoSinglePrice', () => {
+ it('should return empty object when pricing is undefined', () => {
+ const result = resolveVideoSinglePrice(undefined);
+ expect(result).toEqual({});
+ });
+
+ it('should return approximatePrice when approximatePricePerVideo is set', () => {
+ const pricing: Pricing = {
+ approximatePricePerVideo: 0.5,
+ units: [],
+ };
+
+ const result = resolveVideoSinglePrice(pricing);
+ expect(result).toEqual({ approximatePrice: 0.5 });
+ });
+
+ it('should return empty object when approximatePricePerVideo is not set', () => {
+ const pricing: Pricing = {
+ units: [],
+ };
+
+ const result = resolveVideoSinglePrice(pricing);
+ expect(result).toEqual({});
+ });
+
+ it('should return approximatePrice of 0 when approximatePricePerVideo is 0', () => {
+ const pricing: Pricing = {
+ approximatePricePerVideo: 0,
+ units: [],
+ };
+
+ const result = resolveVideoSinglePrice(pricing);
+ expect(result).toEqual({ approximatePrice: 0 });
+ });
+
+ it('should return empty object when approximatePricePerVideo is not a number', () => {
+ const pricing = {
+ approximatePricePerVideo: '0.5' as any,
+ units: [],
+ } as Pricing;
+
+ const result = resolveVideoSinglePrice(pricing);
+ expect(result).toEqual({});
+ });
+});
diff --git a/packages/model-runtime/src/providers/volcengine/video/createVideo.test.ts b/packages/model-runtime/src/providers/volcengine/video/createVideo.test.ts
new file mode 100644
index 00000000000..1f1116fb8c6
--- /dev/null
+++ b/packages/model-runtime/src/providers/volcengine/video/createVideo.test.ts
@@ -0,0 +1,246 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { CreateVideoOptions } from '../../../core/openaiCompatibleFactory';
+import type { CreateVideoPayload } from '../../../types/video';
+import { createVolcengineVideo } from './createVideo';
+
+vi.mock('debug', () => ({
+ default: vi.fn(() => vi.fn()),
+}));
+
+const mockFetch = vi.fn();
+vi.stubGlobal('fetch', mockFetch);
+
+describe('createVolcengineVideo', () => {
+ let payload: CreateVideoPayload;
+ let options: CreateVideoOptions;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+
+ payload = {
+ model: 'doubao-video-model',
+ params: {
+ prompt: 'a beautiful sunset over the ocean',
+ },
+ };
+
+ options = {
+ apiKey: 'test-api-key',
+ provider: 'volcengine',
+ };
+ });
+
+ describe('successful creation', () => {
+ it('should return inferenceId on success', async () => {
+ mockFetch.mockResolvedValue({
+ json: () => Promise.resolve({ id: 'task-abc-123' }),
+ ok: true,
+ });
+
+ const result = await createVolcengineVideo(payload, options);
+
+ expect(result).toEqual({ inferenceId: 'task-abc-123' });
+ });
+
+ it('should send minimal body with only prompt', async () => {
+ mockFetch.mockResolvedValue({
+ json: () => Promise.resolve({ id: 'task-1' }),
+ ok: true,
+ });
+
+ await createVolcengineVideo(payload, options);
+
+ const fetchCall = mockFetch.mock.calls[0];
+ const body = JSON.parse(fetchCall[1].body);
+
+ expect(body.content).toEqual([{ text: 'a beautiful sunset over the ocean', type: 'text' }]);
+ expect(body.model).toBe('doubao-video-model');
+ expect(body.watermark).toBe(false);
+ // Should not include optional params
+ expect(body.ratio).toBeUndefined();
+ expect(body.duration).toBeUndefined();
+ expect(body.seed).toBeUndefined();
+ });
+ });
+
+ describe('content array', () => {
+ it('should add first_frame entry when imageUrl is provided', async () => {
+ mockFetch.mockResolvedValue({
+ json: () => Promise.resolve({ id: 'task-1' }),
+ ok: true,
+ });
+
+ payload.params.imageUrl = 'https://example.com/start.jpg';
+
+ await createVolcengineVideo(payload, options);
+
+ const body = JSON.parse(mockFetch.mock.calls[0][1].body);
+ expect(body.content).toHaveLength(2);
+ expect(body.content[1]).toEqual({
+ image_url: { url: 'https://example.com/start.jpg' },
+ role: 'first_frame',
+ type: 'image_url',
+ });
+ });
+
+ it('should add last_frame entry when endImageUrl is provided', async () => {
+ mockFetch.mockResolvedValue({
+ json: () => Promise.resolve({ id: 'task-1' }),
+ ok: true,
+ });
+
+ payload.params.endImageUrl = 'https://example.com/end.jpg';
+
+ await createVolcengineVideo(payload, options);
+
+ const body = JSON.parse(mockFetch.mock.calls[0][1].body);
+ expect(body.content).toHaveLength(2);
+ expect(body.content[1]).toEqual({
+ image_url: { url: 'https://example.com/end.jpg' },
+ role: 'last_frame',
+ type: 'image_url',
+ });
+ });
+
+ it('should have 3 content elements when both imageUrl and endImageUrl are provided', async () => {
+ mockFetch.mockResolvedValue({
+ json: () => Promise.resolve({ id: 'task-1' }),
+ ok: true,
+ });
+
+ payload.params.imageUrl = 'https://example.com/start.jpg';
+ payload.params.endImageUrl = 'https://example.com/end.jpg';
+
+ await createVolcengineVideo(payload, options);
+
+ const body = JSON.parse(mockFetch.mock.calls[0][1].body);
+ expect(body.content).toHaveLength(3);
+ expect(body.content[0].type).toBe('text');
+ expect(body.content[1].role).toBe('first_frame');
+ expect(body.content[2].role).toBe('last_frame');
+ });
+ });
+
+ describe('optional params', () => {
+ beforeEach(() => {
+ mockFetch.mockResolvedValue({
+ json: () => Promise.resolve({ id: 'task-1' }),
+ ok: true,
+ });
+ });
+
+ it('should map aspectRatio to body.ratio', async () => {
+ payload.params.aspectRatio = '16:9';
+ await createVolcengineVideo(payload, options);
+ const body = JSON.parse(mockFetch.mock.calls[0][1].body);
+ expect(body.ratio).toBe('16:9');
+ });
+
+ it('should map duration to body.duration', async () => {
+ payload.params.duration = 5;
+ await createVolcengineVideo(payload, options);
+ const body = JSON.parse(mockFetch.mock.calls[0][1].body);
+ expect(body.duration).toBe(5);
+ });
+
+ it('should map generateAudio to body.generate_audio', async () => {
+ payload.params.generateAudio = true;
+ await createVolcengineVideo(payload, options);
+ const body = JSON.parse(mockFetch.mock.calls[0][1].body);
+ expect(body.generate_audio).toBe(true);
+ });
+
+ it('should map seed to body.seed', async () => {
+ payload.params.seed = 42;
+ await createVolcengineVideo(payload, options);
+ const body = JSON.parse(mockFetch.mock.calls[0][1].body);
+ expect(body.seed).toBe(42);
+ });
+
+ it('should not include seed when seed is null', async () => {
+ payload.params.seed = null;
+ await createVolcengineVideo(payload, options);
+ const body = JSON.parse(mockFetch.mock.calls[0][1].body);
+ expect(body.seed).toBeUndefined();
+ });
+
+ it('should map resolution to body.resolution', async () => {
+ payload.params.resolution = '1080p';
+ await createVolcengineVideo(payload, options);
+ const body = JSON.parse(mockFetch.mock.calls[0][1].body);
+ expect(body.resolution).toBe('1080p');
+ });
+
+ it('should map cameraFixed to body.camera_fixed', async () => {
+ payload.params.cameraFixed = true;
+ await createVolcengineVideo(payload, options);
+ const body = JSON.parse(mockFetch.mock.calls[0][1].body);
+ expect(body.camera_fixed).toBe(true);
+ });
+
+ it('should map callbackUrl to body.callback_url', async () => {
+ payload.callbackUrl = 'https://example.com/webhook';
+ await createVolcengineVideo(payload, options);
+ const body = JSON.parse(mockFetch.mock.calls[0][1].body);
+ expect(body.callback_url).toBe('https://example.com/webhook');
+ });
+ });
+
+ describe('client config', () => {
+ beforeEach(() => {
+ mockFetch.mockResolvedValue({
+ json: () => Promise.resolve({ id: 'task-1' }),
+ ok: true,
+ });
+ });
+
+ it('should use default baseURL', async () => {
+ await createVolcengineVideo(payload, options);
+
+ const fetchUrl = mockFetch.mock.calls[0][0];
+ expect(fetchUrl).toBe('https://ark.cn-beijing.volces.com/api/v3/contents/generations/tasks');
+ });
+
+ it('should use custom baseURL when provided', async () => {
+ options.baseURL = 'https://custom-endpoint.com/api/v3';
+ await createVolcengineVideo(payload, options);
+
+ const fetchUrl = mockFetch.mock.calls[0][0];
+ expect(fetchUrl).toBe('https://custom-endpoint.com/api/v3/contents/generations/tasks');
+ });
+
+ it('should send Authorization Bearer header', async () => {
+ await createVolcengineVideo(payload, options);
+
+ const fetchHeaders = mockFetch.mock.calls[0][1].headers;
+ expect(fetchHeaders['Authorization']).toBe('Bearer test-api-key');
+ expect(fetchHeaders['Content-Type']).toBe('application/json');
+ });
+ });
+
+ describe('error handling', () => {
+ it('should throw on HTTP error', async () => {
+ mockFetch.mockResolvedValue({
+ ok: false,
+ status: 429,
+ text: () => Promise.resolve('Rate limit exceeded'),
+ });
+
+ await expect(createVolcengineVideo(payload, options)).rejects.toThrow(
+ 'Volcengine video API error: 429 Rate limit exceeded',
+ );
+ });
+
+ it('should throw when response has no id', async () => {
+ mockFetch.mockResolvedValue({
+ json: () => Promise.resolve({}),
+ ok: true,
+ });
+
+ await expect(createVolcengineVideo(payload, options)).rejects.toThrow(
+ 'Invalid response: missing task id',
+ );
+ });
+ });
+});
diff --git a/packages/model-runtime/src/providers/volcengine/video/handleCreateVideoWebhook.test.ts b/packages/model-runtime/src/providers/volcengine/video/handleCreateVideoWebhook.test.ts
new file mode 100644
index 00000000000..d9a818f55e3
--- /dev/null
+++ b/packages/model-runtime/src/providers/volcengine/video/handleCreateVideoWebhook.test.ts
@@ -0,0 +1,177 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { handleVolcengineVideoWebhook } from './handleCreateVideoWebhook';
+
+vi.mock('debug', () => ({
+ default: vi.fn(() => vi.fn()),
+}));
+
+describe('handleVolcengineVideoWebhook', () => {
+ describe('intermediate statuses', () => {
+ it('should return pending for queued status', async () => {
+ const result = await handleVolcengineVideoWebhook({
+ body: { status: 'queued' },
+ });
+
+ expect(result).toEqual({ status: 'pending' });
+ });
+
+ it('should return pending for running status', async () => {
+ const result = await handleVolcengineVideoWebhook({
+ body: { status: 'running' },
+ });
+
+ expect(result).toEqual({ status: 'pending' });
+ });
+ });
+
+ describe('succeeded', () => {
+ it('should return full success result with all fields', async () => {
+ const result = await handleVolcengineVideoWebhook({
+ body: {
+ content: { video_url: 'https://example.com/video.mp4' },
+ generate_audio: true,
+ id: 'task-123',
+ model: 'doubao-video',
+ status: 'succeeded',
+ usage: { completion_tokens: 1000, total_tokens: 1200 },
+ },
+ });
+
+ expect(result).toEqual({
+ generateAudio: true,
+ inferenceId: 'task-123',
+ model: 'doubao-video',
+ status: 'success',
+ usage: { completionTokens: 1000, totalTokens: 1200 },
+ videoUrl: 'https://example.com/video.mp4',
+ });
+ });
+
+ it('should return undefined usage when usage is missing', async () => {
+ const result = await handleVolcengineVideoWebhook({
+ body: {
+ content: { video_url: 'https://example.com/video.mp4' },
+ id: 'task-123',
+ status: 'succeeded',
+ },
+ });
+
+ expect(result).toMatchObject({
+ inferenceId: 'task-123',
+ status: 'success',
+ usage: undefined,
+ videoUrl: 'https://example.com/video.mp4',
+ });
+ });
+
+ it('should fallback totalTokens to completionTokens when total_tokens is missing', async () => {
+ const result = await handleVolcengineVideoWebhook({
+ body: {
+ content: { video_url: 'https://example.com/video.mp4' },
+ id: 'task-123',
+ status: 'succeeded',
+ usage: { completion_tokens: 800 },
+ },
+ });
+
+ expect(result).toMatchObject({
+ status: 'success',
+ usage: { completionTokens: 800, totalTokens: 800 },
+ });
+ });
+
+ it('should throw when id is missing on succeeded', async () => {
+ await expect(
+ handleVolcengineVideoWebhook({
+ body: {
+ content: { video_url: 'https://example.com/video.mp4' },
+ status: 'succeeded',
+ },
+ }),
+ ).rejects.toThrow('Missing task id');
+ });
+
+ it('should throw when video_url is missing on succeeded', async () => {
+ await expect(
+ handleVolcengineVideoWebhook({
+ body: {
+ content: {},
+ id: 'task-123',
+ status: 'succeeded',
+ },
+ }),
+ ).rejects.toThrow('Missing video_url');
+ });
+
+ it('should throw when content is undefined on succeeded', async () => {
+ await expect(
+ handleVolcengineVideoWebhook({
+ body: {
+ id: 'task-123',
+ status: 'succeeded',
+ },
+ }),
+ ).rejects.toThrow('Missing video_url');
+ });
+ });
+
+ describe('error statuses', () => {
+ it('should return error message from failed status', async () => {
+ const result = await handleVolcengineVideoWebhook({
+ body: {
+ error: { message: 'Content policy violation' },
+ id: 'task-123',
+ status: 'failed',
+ },
+ });
+
+ expect(result).toEqual({
+ error: 'Content policy violation',
+ inferenceId: 'task-123',
+ status: 'error',
+ });
+ });
+
+ it('should return expired message for expired status', async () => {
+ const result = await handleVolcengineVideoWebhook({
+ body: {
+ id: 'task-123',
+ status: 'expired',
+ },
+ });
+
+ expect(result).toEqual({
+ error: 'Video generation task expired',
+ inferenceId: 'task-123',
+ status: 'error',
+ });
+ });
+
+ it('should return unknown error for unknown status without error message', async () => {
+ const result = await handleVolcengineVideoWebhook({
+ body: {
+ id: 'task-123',
+ status: 'unknown_status',
+ },
+ });
+
+ expect(result).toEqual({
+ error: 'Unknown error',
+ inferenceId: 'task-123',
+ status: 'error',
+ });
+ });
+
+ it('should throw when id is missing on failed status', async () => {
+ await expect(
+ handleVolcengineVideoWebhook({
+ body: {
+ error: { message: 'some error' },
+ status: 'failed',
+ },
+ }),
+ ).rejects.toThrow('Missing task id');
+ });
+ });
+});