1、项目级规则增加自动化测试规则;2、修正代码风险

This commit is contained in:
wttwins
2025-12-20 20:13:23 +08:00
parent c81ffb4c19
commit 30b237e95b
4 changed files with 496 additions and 8 deletions

View File

@@ -18,13 +18,21 @@
- Ask the user: "代码修改已完成,是否需要创建 git 提交?"
- Wait for user's explicit approval before proceeding.
- Only execute git commands after receiving clear confirmation (e.g., "是", "提交", "commit", "好的").
2. **提交前必须展示变更摘要 (Show Changes Summary)**
- Before committing, always run `git status` and `git diff` to show what will be committed.
- Present a summary of changes to the user for review.
3. **提交信息规范 (Commit Message Convention)**
- Use conventional commit format: `<type>: <description>`
- Types: `feat`, `fix`, `docs`, `style`, `refactor`, `test`, `chore`, `ci`
- Description must be clear and concise in Chinese.
- **🚫 严禁添加 AI 工具署名 (No AI Tool Attribution)**:
- Do NOT add any Claude Code, AI assistant, or co-authorship references
- Do NOT include lines like "Generated with Claude Code"
- Do NOT add "Co-Authored-By: Claude" or similar attributions
- Keep commit messages clean and professional without AI tool mentions
- This prevents GitHub from showing AI tools as repository collaborators
# Front-end Internationalization (i18n) Rules
1. **🚫 严禁硬编码 (No Hardcoded Strings)**
@@ -64,4 +72,87 @@
- Before implementing page/component changes, you MUST ask:
- "这个功能在移动端需要特殊处理吗?"
- "移动端和 PC 端的布局是否需要不同?"
- If unclear, propose both mobile and desktop designs for user approval.
- If unclear, propose both mobile and desktop designs for user approval.
# Testing Rules (测试规则)
1. **🔄 自动化测试触发 (Automated Testing)**
- After completing code modifications (without errors), automatically run tests based on change scope
- Do NOT run `npm run build` unless explicitly requested by the user
- Do NOT wait for user confirmation to run tests — this is an automated quality gate
- Use smart triggers and tiered testing strategy (see below)
2. **🎯 智能测试触发 (Smart Test Triggers)**
**自动运行测试** (需要测试的情况):
- 修改 `.ts`、`.tsx` 源代码文件
- 修改 API 路由 (`src/app/api/*`)
- 修改核心库代码 (`src/lib/*`)
- 修改数据库相关代码 (`prisma/*`)
- 修改组件代码 (`src/components/*`)
- 修改测试文件本身 (`src/__tests__/*`)
**跳过测试** (不需要测试的情况):
- 仅修改文档文件 (`.md`, `.txt`, `doc/*`)
- 仅修改配置示例 (`.env.example`, `.gitignore`, `.cursorrulers`)
- 仅修改样式文件 (`.css`, 纯样式调整)
- 仅修改注释或代码格式化 (不改变逻辑)
**用户确认** (不确定是否需要测试时):
- 修改构建配置 (`package.json`, `tsconfig.json`, `next.config.js`)
- 修改测试配置 (`vitest.config.ts`, `playwright.config.ts`)
3. **🚀 分级测试策略 (Tiered Testing Strategy)**
**Level 1 - 快速验证** (< 1秒):
- 适用于: 单个函数/组件小改动
- 运行: 相关的单元测试子集
- 示例: `vitest run src/__tests__/unit/utils.test.ts`
**Level 2 - 标准验证** (~3秒):
- 适用于: 多文件修改、新功能开发
- 运行: 完整单元测试
- 命令: `npm run test:unit`
**Level 3 - 完整验证** (~5秒) ⭐ **默认级别**:
- 适用于: API/数据库修改、核心逻辑变更
- 运行: 单元测试 + 集成测试
- 命令: `npm run test:unit && npm run test:integration`
**Level 4 - 发布准备** (5-10分钟):
- 适用于: 准备提交 PR、发布前验证
- 运行: 所有测试 + 类型检查 + 构建
- 命令: `npm run test && npm run build`
- ⚠️ **仅在用户明确要求时运行**
4. **📊 测试结果处理 (Test Results Handling)**
- **If tests PASS**: Report success with summary and proceed
- **If tests FAIL**:
- Analyze the failure and attempt to fix the issue
- Re-run the failed tests after fixing
- Only report completion after ALL tests pass
- Always show a clear summary of test results to the user:
- Number of tests passed/failed
- Execution time
- Failed test details (if any)
5. **⚠️ 测试覆盖要求 (Test Coverage Requirements)**
- When adding new features:
- Write unit tests for new functions/classes
- Write integration tests for new API routes
- Update existing tests if behavior changes
- When modifying existing code:
- Ensure related tests still pass
- Update tests if contracts change
- Add tests for new edge cases
- When fixing bugs:
- Add a test that reproduces the bug
- Verify the test fails before fix
- Verify the test passes after fix
6. **🎯 最佳实践 (Best Practices)**
- Prefer Level 3 (完整验证) for most development work
- Use Level 1-2 for rapid iteration during development
- Reserve Level 4 for pre-commit/pre-PR validation
- If unsure which level to use, default to Level 3
- Build (`npm run build`) should only run in CI/CD or when explicitly requested

View File

@@ -39,11 +39,8 @@ test('Admin can configure OpenAI settings with multi-instance support', async ({
const baseURL = 'https://new.xxx.net/v1';
const modelName = 'claude-haiku-4.5';
// Instance Name Input (in the instance form)
const instanceNameInput = page.locator('input[placeholder*="智谱"], input[placeholder*="GLM"]');
if (await instanceNameInput.isVisible()) {
await instanceNameInput.fill(instanceName);
}
// Instance Name Input - use the actual placeholder from the component
await page.locator('input[placeholder="e.g. 智谱 GLM-4V"]').fill(instanceName);
// API Key Input associated by placeholder
await page.locator('input[placeholder="sk-..."]').fill(apiKey);

View File

@@ -0,0 +1,399 @@
/**
* Azure OpenAI Provider 单元测试
*
* 测试 Azure OpenAI 服务初始化和错误处理
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
// Mock Azure OpenAI SDK
vi.mock('openai', () => {
return {
AzureOpenAI: class MockAzureOpenAI {
chat = {
completions: {
create: vi.fn(),
},
};
},
};
});
// Mock logger
vi.mock('@/lib/logger', () => ({
createLogger: vi.fn(() => ({
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
box: vi.fn(),
divider: vi.fn(),
})),
}));
// Mock config
vi.mock('@/lib/config', () => ({
getAppConfig: vi.fn(() => ({
aiProvider: 'azure',
azure: {
apiKey: 'test-key',
endpoint: 'https://test.openai.azure.com',
deploymentName: 'gpt-4o',
apiVersion: '2024-02-15-preview',
},
})),
}));
// Mock tag service
vi.mock('@/lib/ai/tag-service', () => ({
getMathTagsFromDB: vi.fn(() => Promise.resolve([])),
getTagsFromDB: vi.fn(() => Promise.resolve([])),
}));
// Mock jsonrepair
vi.mock('jsonrepair', () => ({
jsonrepair: vi.fn((str) => str),
}));
// Delayed import to ensure mocks are applied
import { AzureOpenAIProvider } from '@/lib/ai/azure-provider';
describe('Azure OpenAI Provider 初始化', () => {
beforeEach(() => {
vi.clearAllMocks();
});
describe('构造函数验证', () => {
it('缺少 API Key 时应该抛出 AI_AUTH_ERROR', () => {
expect(() => new AzureOpenAIProvider({
endpoint: 'https://test.openai.azure.com',
deploymentName: 'gpt-4o',
})).toThrow('AI_AUTH_ERROR');
expect(() => new AzureOpenAIProvider({
endpoint: 'https://test.openai.azure.com',
deploymentName: 'gpt-4o',
})).toThrow('AZURE_OPENAI_API_KEY is required');
});
it('API Key 为空字符串时应该抛出 AI_AUTH_ERROR', () => {
expect(() => new AzureOpenAIProvider({
apiKey: '',
endpoint: 'https://test.openai.azure.com',
deploymentName: 'gpt-4o',
})).toThrow('AI_AUTH_ERROR');
});
it('缺少 endpoint 时应该抛出 AI_AUTH_ERROR', () => {
expect(() => new AzureOpenAIProvider({
apiKey: 'test-key',
deploymentName: 'gpt-4o',
})).toThrow('AI_AUTH_ERROR');
expect(() => new AzureOpenAIProvider({
apiKey: 'test-key',
deploymentName: 'gpt-4o',
})).toThrow('AZURE_OPENAI_ENDPOINT is required');
});
it('endpoint 为空字符串时应该抛出 AI_AUTH_ERROR', () => {
expect(() => new AzureOpenAIProvider({
apiKey: 'test-key',
endpoint: '',
deploymentName: 'gpt-4o',
})).toThrow('AI_AUTH_ERROR');
});
it('缺少 deploymentName 时应该抛出 AI_AUTH_ERROR', () => {
expect(() => new AzureOpenAIProvider({
apiKey: 'test-key',
endpoint: 'https://test.openai.azure.com',
})).toThrow('AI_AUTH_ERROR');
expect(() => new AzureOpenAIProvider({
apiKey: 'test-key',
endpoint: 'https://test.openai.azure.com',
})).toThrow('AZURE_OPENAI_DEPLOYMENT is required');
});
it('deploymentName 为空字符串时应该抛出 AI_AUTH_ERROR', () => {
expect(() => new AzureOpenAIProvider({
apiKey: 'test-key',
endpoint: 'https://test.openai.azure.com',
deploymentName: '',
})).toThrow('AI_AUTH_ERROR');
});
it('有效配置时应该成功创建实例', () => {
const provider = new AzureOpenAIProvider({
apiKey: 'test-key',
endpoint: 'https://test.openai.azure.com',
deploymentName: 'gpt-4o',
});
expect(provider).toBeDefined();
expect(typeof provider.analyzeImage).toBe('function');
expect(typeof provider.generateSimilarQuestion).toBe('function');
expect(typeof provider.reanswerQuestion).toBe('function');
});
it('应该使用默认 API 版本', () => {
const provider = new AzureOpenAIProvider({
apiKey: 'test-key',
endpoint: 'https://test.openai.azure.com',
deploymentName: 'gpt-4o',
});
expect(provider).toBeDefined();
});
it('应该支持自定义 API 版本', () => {
const provider = new AzureOpenAIProvider({
apiKey: 'test-key',
endpoint: 'https://test.openai.azure.com',
deploymentName: 'gpt-4o',
apiVersion: '2024-06-01',
});
expect(provider).toBeDefined();
});
it('应该支持自定义 model 显示名称', () => {
const provider = new AzureOpenAIProvider({
apiKey: 'test-key',
endpoint: 'https://test.openai.azure.com',
deploymentName: 'my-gpt-4o-deployment',
model: 'gpt-4o',
});
expect(provider).toBeDefined();
});
});
describe('方法验证', () => {
it('analyzeImage 方法应该存在并且是函数', () => {
const provider = new AzureOpenAIProvider({
apiKey: 'test-key',
endpoint: 'https://test.openai.azure.com',
deploymentName: 'gpt-4o',
});
expect(provider.analyzeImage).toBeDefined();
expect(typeof provider.analyzeImage).toBe('function');
});
it('generateSimilarQuestion 方法应该存在并且是函数', () => {
const provider = new AzureOpenAIProvider({
apiKey: 'test-key',
endpoint: 'https://test.openai.azure.com',
deploymentName: 'gpt-4o',
});
expect(provider.generateSimilarQuestion).toBeDefined();
expect(typeof provider.generateSimilarQuestion).toBe('function');
});
it('reanswerQuestion 方法应该存在并且是函数', () => {
const provider = new AzureOpenAIProvider({
apiKey: 'test-key',
endpoint: 'https://test.openai.azure.com',
deploymentName: 'gpt-4o',
});
expect(provider.reanswerQuestion).toBeDefined();
expect(typeof provider.reanswerQuestion).toBe('function');
});
});
});
describe('Azure OpenAI Provider 响应解析', () => {
let provider: AzureOpenAIProvider;
beforeEach(() => {
vi.clearAllMocks();
provider = new AzureOpenAIProvider({
apiKey: 'test-key',
endpoint: 'https://test.openai.azure.com',
deploymentName: 'gpt-4o',
});
});
describe('parseResponse', () => {
it('应该正确解析包含所有必需标签的响应', () => {
const mockResponse = `
<question_text>求函数 f(x) = x^2 的最小值</question_text>
<answer_text>最小值为 0</answer_text>
<analysis>这是一个二次函数,开口向上,顶点在原点,因此最小值为 0</analysis>
<subject>数学</subject>
<knowledge_points>二次函数, 函数最值</knowledge_points>
<requires_image>true</requires_image>
`.trim();
// Access private method via type assertion
const result = (provider as any).parseResponse(mockResponse);
expect(result.questionText).toBe('求函数 f(x) = x^2 的最小值');
expect(result.answerText).toBe('最小值为 0');
expect(result.analysis).toContain('二次函数');
expect(result.subject).toBe('数学');
expect(result.knowledgePoints).toContain('二次函数');
expect(result.knowledgePoints).toContain('函数最值');
expect(result.requiresImage).toBe(true);
});
it('应该正确处理 requiresImage 为 false', () => {
const mockResponse = `
<question_text>测试题目</question_text>
<answer_text>测试答案</answer_text>
<analysis>测试解析</analysis>
<requires_image>false</requires_image>
`.trim();
const result = (provider as any).parseResponse(mockResponse);
expect(result.requiresImage).toBe(false);
});
it('应该正确处理无效学科返回默认值"其他"', () => {
const mockResponse = `
<question_text>测试题目</question_text>
<answer_text>测试答案</answer_text>
<analysis>测试解析</analysis>
<subject>无效学科</subject>
`.trim();
const result = (provider as any).parseResponse(mockResponse);
expect(result.subject).toBe('其他');
});
it('应该正确分割知识点(逗号分隔)', () => {
const mockResponse = `
<question_text>测试题目</question_text>
<answer_text>测试答案</answer_text>
<analysis>测试解析</analysis>
<knowledge_points>知识点1, 知识点2, 知识点3</knowledge_points>
`.trim();
const result = (provider as any).parseResponse(mockResponse);
expect(result.knowledgePoints).toHaveLength(3);
expect(result.knowledgePoints).toContain('知识点1');
expect(result.knowledgePoints).toContain('知识点2');
expect(result.knowledgePoints).toContain('知识点3');
});
it('应该正确分割知识点(中文逗号分隔)', () => {
const mockResponse = `
<question_text>测试题目</question_text>
<answer_text>测试答案</answer_text>
<analysis>测试解析</analysis>
<knowledge_points>知识点1,知识点2,知识点3</knowledge_points>
`.trim();
const result = (provider as any).parseResponse(mockResponse);
expect(result.knowledgePoints).toHaveLength(3);
});
it('缺少必需标签时应该抛出错误', () => {
const mockResponse = `
<question_text>测试题目</question_text>
<answer_text>测试答案</answer_text>
`.trim();
expect(() => (provider as any).parseResponse(mockResponse)).toThrow('Missing critical XML tags');
});
});
describe('extractTag', () => {
it('应该正确提取标签内容', () => {
const text = '<test>content</test>';
const result = (provider as any).extractTag(text, 'test');
expect(result).toBe('content');
});
it('应该去除首尾空格', () => {
const text = '<test> content with spaces </test>';
const result = (provider as any).extractTag(text, 'test');
expect(result).toBe('content with spaces');
});
it('标签不存在时应该返回 null', () => {
const text = '<other>content</other>';
const result = (provider as any).extractTag(text, 'test');
expect(result).toBeNull();
});
it('应该处理多行内容', () => {
const text = `
<test>
line 1
line 2
line 3
</test>
`.trim();
const result = (provider as any).extractTag(text, 'test');
expect(result).toContain('line 1');
expect(result).toContain('line 2');
expect(result).toContain('line 3');
});
});
});
describe('Azure OpenAI Provider 错误处理', () => {
let provider: AzureOpenAIProvider;
beforeEach(() => {
vi.clearAllMocks();
provider = new AzureOpenAIProvider({
apiKey: 'test-key',
endpoint: 'https://test.openai.azure.com',
deploymentName: 'gpt-4o',
});
});
describe('handleError', () => {
it('应该将网络错误转换为 AI_CONNECTION_FAILED', () => {
const networkError = new Error('fetch failed');
expect(() => (provider as any).handleError(networkError)).toThrow('AI_CONNECTION_FAILED');
});
it('应该将连接错误转换为 AI_CONNECTION_FAILED', () => {
const connectionError = new Error('Failed to connect to server');
expect(() => (provider as any).handleError(connectionError)).toThrow('AI_CONNECTION_FAILED');
});
it('应该将认证错误转换为 AI_AUTH_ERROR', () => {
const authError = new Error('Unauthorized: Invalid API key');
expect(() => (provider as any).handleError(authError)).toThrow('AI_AUTH_ERROR');
});
it('应该将 401 错误转换为 AI_AUTH_ERROR', () => {
const authError = new Error('Request failed with status 401');
expect(() => (provider as any).handleError(authError)).toThrow('AI_AUTH_ERROR');
});
it('应该将 JSON 解析错误转换为 AI_RESPONSE_ERROR', () => {
const parseError = new Error('Invalid JSON format');
expect(() => (provider as any).handleError(parseError)).toThrow('AI_RESPONSE_ERROR');
});
it('未知错误应该转换为 AI_UNKNOWN_ERROR', () => {
const unknownError = new Error('Something went wrong');
expect(() => (provider as any).handleError(unknownError)).toThrow('AI_UNKNOWN_ERROR');
});
it('非 Error 对象应该转换为 AI_UNKNOWN_ERROR', () => {
const unknownError = 'string error';
expect(() => (provider as any).handleError(unknownError)).toThrow('AI_UNKNOWN_ERROR');
});
});
});

View File

@@ -2,6 +2,7 @@ import { NextResponse } from "next/server";
import { getAppConfig, updateAppConfig } from "@/lib/config";
import { internalError } from "@/lib/api-errors";
import { createLogger } from "@/lib/logger";
import { OpenAIInstance } from "@/types/api";
const logger = createLogger('api:settings');
@@ -25,10 +26,10 @@ export async function POST(req: Request) {
// For OpenAI instances, preserve original keys for masked entries
if (body.openai?.instances) {
const currentInstances = currentConfig.openai?.instances || [];
body.openai.instances = body.openai.instances.map((instance: any) => {
body.openai.instances = body.openai.instances.map((instance: OpenAIInstance) => {
if (instance.apiKey === '********') {
// 查找原有实例并保留其 API Key
const originalInstance = currentInstances.find((i: any) => i.id === instance.id);
const originalInstance = currentInstances.find((i: OpenAIInstance) => i.id === instance.id);
return {
...instance,
apiKey: originalInstance?.apiKey || '',