From 825b4bf2d937f11be3a2c48542ebd35d7444caed Mon Sep 17 00:00:00 2001 From: margrop <1731827+margrop@users.noreply.github.com> Date: Sat, 31 Oct 2026 11:43:37 +0800 Subject: [PATCH] =?UTF-8?q?test:=20=E8=A1=A5=E5=85=85=20AI=20=E8=AE=BE?= =?UTF-8?q?=E7=BD=AE=E6=A0=A1=E9=AA=8C=E5=92=8C=E4=B8=8A=E4=BC=A0=E5=9B=BE?= =?UTF-8?q?=E7=89=87=E5=8E=8B=E7=BC=A9=E7=9A=84=E5=8D=95=E5=85=83=E6=B5=8B?= =?UTF-8?q?=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- .../unit/ai-config-validation.test.ts | 46 +++++++++ src/__tests__/unit/image-utils.test.ts | 98 +++++++++++++++++++ 2 files changed, 144 insertions(+) create mode 100644 src/__tests__/unit/ai-config-validation.test.ts create mode 100644 src/__tests__/unit/image-utils.test.ts diff --git a/src/__tests__/unit/ai-config-validation.test.ts b/src/__tests__/unit/ai-config-validation.test.ts new file mode 100644 index 00000000..4f74d08d --- /dev/null +++ b/src/__tests__/unit/ai-config-validation.test.ts @@ -0,0 +1,46 @@ +/** + * 保存 AI 设置前的必填项校验 + */ +import { describe, it, expect } from 'vitest'; +import { validateAiConfig } from '@/lib/ai-config-validation'; +import { translations } from '@/lib/translations'; +import type { AppConfig } from '@/types/api'; + +const t = translations.zh; +const ai = t.settings.ai; +const openaiInstance = { id: 'i1', name: '我的渠道', apiKey: 'sk-1', baseUrl: 'https://api.example.com/v1', model: 'gpt' }; +const config = (overrides: Partial) => ({ aiProvider: 'gemini', ...overrides }) as AppConfig; + +describe('validateAiConfig', () => { + it('时区无效时提示,未设置时区按默认值通过', () => { + expect(validateAiConfig(config({ timeZone: 'Mars/Base' }), t)).toBe(t.settings.general.invalidTimeZone); + expect(validateAiConfig(config({}), t)).toBeNull(); + expect(validateAiConfig(config({ timeZone: 'Asia/Shanghai' }), t)).toBeNull(); + }); + + it('OpenAI 兼容渠道的每个实例都要有名称、API Key、地址和模型', () => { + const check = (patch: Record) => + validateAiConfig(config({ aiProvider: 'openai', openai: { instances: [openaiInstance, { ...openaiInstance, ...patch }] } as AppConfig['openai'] }), t); + + expect(check({})).toBeNull(); + expect(check({ name: ' ' })).toBe(ai.validationNameRequired); + expect(check({ apiKey: '' })).toBe(ai.validationApiKeyRequired); + expect(check({ baseUrl: '' })).toBe(ai.validationBaseUrlRequired); + expect(check({ model: ' ' })).toBe(ai.validationModelRequired); + }); + + it('Azure 渠道要有端点、部署名和 API Key', () => { + const azure = { endpoint: 'https://x.openai.azure.com', deploymentName: 'gpt', apiKey: 'k' }; + const check = (patch: Record) => + validateAiConfig(config({ aiProvider: 'azure', azure: { ...azure, ...patch } as AppConfig['azure'] }), t); + + expect(check({})).toBeNull(); + expect(check({ endpoint: '' })).toBe(ai.validationAzureEndpointRequired); + expect(check({ deploymentName: '' })).toBe(ai.validationAzureDeploymentRequired); + expect(check({ apiKey: '' })).toBe(ai.validationApiKeyRequired); + }); + + it('其他渠道不检查 OpenAI 和 Azure 的字段', () => { + expect(validateAiConfig(config({ aiProvider: 'gemini', azure: {} as AppConfig['azure'] }), t)).toBeNull(); + }); +}); diff --git a/src/__tests__/unit/image-utils.test.ts b/src/__tests__/unit/image-utils.test.ts new file mode 100644 index 00000000..c2e6f77b --- /dev/null +++ b/src/__tests__/unit/image-utils.test.ts @@ -0,0 +1,98 @@ +/** + * 上传前的图片处理:1MB 以内直接转 Base64,超过则缩放并逐步降低 JPEG 质量 + */ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; + +vi.mock('@/lib/frontend-logger', () => ({ frontendLogger: { info: vi.fn(), error: vi.fn() } })); + +import { compressImage, processImageFile } from '@/lib/image-utils'; + +const MB = 1024 * 1024; +const fileOfSize = (bytes: number) => new File([new Uint8Array(bytes)], 'q.png', { type: 'image/png' }); +/** 生成指定解码后大小(MB)的 data URL */ +const dataUrlOfMB = (mb: number) => 'data:image/jpeg;base64,' + 'A'.repeat(Math.ceil((mb * MB * 4) / 3)); + +let imageSize = { width: 1000, height: 500 }; +let toDataURL: ReturnType; +let drawImage: ReturnType; +let canvas: { width: number; height: number; getContext: () => unknown; toDataURL: typeof toDataURL }; + +beforeEach(() => { + imageSize = { width: 1000, height: 500 }; + drawImage = vi.fn(); + toDataURL = vi.fn(() => dataUrlOfMB(0.5)); + canvas = { width: 0, height: 0, getContext: () => ({ drawImage }), toDataURL }; + vi.spyOn(document, 'createElement').mockImplementation(((tag: string) => { + if (tag === 'canvas') return canvas; + throw new Error(`unexpected element ${tag}`); + }) as typeof document.createElement); + // jsdom 不会真正解码图片,加载时立即回调 + vi.stubGlobal('Image', class { + width = imageSize.width; + height = imageSize.height; + onload: (() => void) | null = null; + onerror: (() => void) | null = null; + set src(_value: string) { setTimeout(() => this.onload?.(), 0); } + }); +}); + +afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllGlobals(); +}); + +describe('processImageFile', () => { + it('1MB 以内的图片原样转成 data URL,不经过压缩', async () => { + const result = await processImageFile(fileOfSize(1000)); + + expect(result).toMatch(/^data:image\/png;base64,/); + expect(toDataURL).not.toHaveBeenCalled(); + }); + + it('超过 1MB 时压缩为 JPEG', async () => { + const result = await processImageFile(fileOfSize(2 * MB)); + + expect(result).toBe(dataUrlOfMB(0.5)); + expect(toDataURL).toHaveBeenCalledWith('image/jpeg', 0.8); + }); +}); + +describe('compressImage', () => { + it('宽度超过上限时按比例缩小', async () => { + imageSize = { width: 4000, height: 3000 }; + + await compressImage(fileOfSize(10), 1, 1920); + + expect([canvas.width, canvas.height]).toEqual([1920, 1440]); + expect(drawImage).toHaveBeenCalledWith(expect.anything(), 0, 0, 1920, 1440); + }); + + it('不超过上限的图片保持原尺寸', async () => { + await compressImage(fileOfSize(10)); + expect([canvas.width, canvas.height]).toEqual([1000, 500]); + }); + + it('仍然过大时逐步降低质量,满足大小后立即停止', async () => { + toDataURL + .mockReturnValueOnce(dataUrlOfMB(3)) + .mockReturnValueOnce(dataUrlOfMB(2)) + .mockReturnValueOnce(dataUrlOfMB(0.9)); + + const result = await compressImage(fileOfSize(10), 1); + + expect(result).toBe(dataUrlOfMB(0.9)); + expect(toDataURL.mock.calls.map(([, q]) => Number(q.toFixed(1)))).toEqual([0.8, 0.7, 0.6]); + }); + + it('质量降到下限仍过大时返回最后一次结果,不会无限循环', async () => { + toDataURL.mockReturnValue(dataUrlOfMB(5)); + + await expect(compressImage(fileOfSize(10), 1)).resolves.toBe(dataUrlOfMB(5)); + expect(toDataURL.mock.calls.length).toBeLessThanOrEqual(9); + }); + + it('无法获取 Canvas 上下文时报错', async () => { + canvas.getContext = () => null; + await expect(compressImage(fileOfSize(10))).rejects.toThrow('无法获取 Canvas 上下文'); + }); +});