Commit 8cb6f6d4 by Jaxon

ci: 添加 AI 单元测试生成 CI 任务和脚本

1 parent ece9d645
Pipeline #57 for 8cb6f6d4 failed in 0 seconds
# GitLab CI 配置:用于 AI 生成单元测试
# 此模板设计用于被包含在主 .gitlab-ci.yml 文件中,或作为独立配置使用。
stages:
- test
ai-unit-test-generation:
# 定义所属阶段为测试阶段
stage: test
# 使用 Node.js 24 镜像环境运行脚本
image: node:24
script:
- echo "开始执行 AI 单元测试生成..."
# 运行 AI 生成测试脚本
- node scripts/ci/ai-test-gen.mjs
rules:
# 规则:在除 main 和 dev 分支以外的所有分支上运行
- if: "$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH || $CI_COMMIT_BRANCH == 'dev'"
when: never
# 规则:如果是合并请求(Merge Request)触发的流水线,则不运行
- if: "$CI_PIPELINE_SOURCE == 'push' && $CI_COMMIT_BRANCH"
when: always
# 允许此任务失败,不会导致整个流水线失败(仅作为辅助工具)
allow_failure: true
variables:
# 以下变量需要在 GitLab CI/CD 设置中配置(建议设置为 Masked 和 Protected):
# QWEN_API_KEY: 您的通义千问 (DashScope) API 密钥
# GITLAB_TOKEN: 具有 'api' 权限的 GitLab 个人访问令牌 (PAT) 或项目访问令牌。
# (CI_JOB_TOKEN 可能适用于某些操作,但通常发布评论的权限受限)
# 可选变量:
# QWEN_MODEL: "qwen-coder-plus" (推荐代码模型) 或 "qwen-plus" (默认)
# QWEN_API_URL: "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions" (默认)
import { execSync } from "node:child_process";
import fs from "node:fs";
import https from "node:https";
import path from "node:path";
// 配置
const QWEN_API_KEY = process.env.QWEN_API_KEY;
// 默认使用 DashScope OpenAI 兼容接口
const QWEN_API_URL = process.env.QWEN_API_URL || "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions";
const QWEN_MODEL = process.env.QWEN_MODEL || "qwen-coder-plus";
const GITLAB_TOKEN = process.env.GITLAB_TOKEN || process.env.CI_JOB_TOKEN;
const PROJECT_ID = process.env.CI_PROJECT_ID;
const COMMIT_SHA = process.env.CI_COMMIT_SHA;
// 例如:https://gitlab.com/api/v4
const API_URL = process.env.CI_API_V4_URL;
if (!QWEN_API_KEY) {
console.error("错误: 未设置 QWEN_API_KEY 环境变量。");
process.exit(1);
}
if (!GITLAB_TOKEN) {
console.error("错误: 未设置 GITLAB_TOKEN 环境变量。");
process.exit(1);
}
if (!PROJECT_ID || !COMMIT_SHA || !API_URL) {
console.error("错误: 缺少必要的 CI 环境变量 (CI_PROJECT_ID, CI_COMMIT_SHA, CI_API_V4_URL)。");
process.exit(1);
}
// 发送 HTTPS 请求的辅助函数
function request(url, options, data) {
return new Promise((resolve, reject) => {
const req = https.request(url, options, (res) => {
let body = "";
res.on("data", (chunk) => body += chunk);
res.on("end", () => {
if (res.statusCode >= 200 && res.statusCode < 300) {
try {
resolve(JSON.parse(body));
} catch {
// 如果不是 JSON
resolve(body);
}
} else {
reject(new Error(`请求失败,状态码 ${res.statusCode}: ${body}`));
}
});
});
req.on("error", (e) => reject(e));
if (data) {
req.write(typeof data === "string" ? data : JSON.stringify(data));
}
req.end();
});
}
// 获取变更的文件
function getChangedFiles() {
try {
// 检查 git 是否可用以及是否在 git 仓库内
// 在 GitLab CI 中,通常是浅克隆 (shallow fetch)。
// 我们尝试与上一次提交进行差异比较。
const output = execSync("git diff --name-only HEAD~1 HEAD", { encoding: "utf8" });
return output.split("\n").filter(line => line.trim() !== "");
} catch (error) {
console.warn("警告: 无法通过 git diff 获取变更文件。假设没有变更或发生错误:", error.message);
return [];
}
}
async function generateUnitTest(filePath, content) {
const prompt = `You are an expert software engineer and unit test writer.
Your task is to write a comprehensive unit test for the following code file.
File Path: ${filePath}
Language: ${path.extname(filePath).slice(1)}
Source Code:
\`\`\`${path.extname(filePath).slice(1)}
${content}
\`\`\`
Please provide only the unit test code. Use Vitest or Jest if it's JavaScript/TypeScript.
If it's another language, use the standard testing framework for that language.
Wrap the code in a markdown code block.
Add brief comments explaining the test cases in Chinese.`;
try {
const response = await request(QWEN_API_URL, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${QWEN_API_KEY}`
}
}, {
model: QWEN_MODEL,
messages: [
{ role: "system", content: "You are a helpful assistant that writes unit tests." },
{ role: "user", content: prompt }
]
});
if (response.choices && response.choices.length > 0) {
return response.choices[0].message.content;
} else {
console.error("Qwen API 返回结果为空:", response);
return null;
}
} catch (error) {
console.error("调用 Qwen API 出错:", error);
return null;
}
}
async function postGitLabComment(filePath, testCode) {
const commentBody = `### 🤖 AI 生成的单元测试 \`${filePath}\`
${testCode}
_Generated by Qwen AI_`;
const url = `${API_URL}/projects/${PROJECT_ID}/repository/commits/${COMMIT_SHA}/comments`;
try {
await request(url, {
method: "POST",
headers: {
"PRIVATE-TOKEN": GITLAB_TOKEN,
"Content-Type": "application/json"
}
}, {
note: commentBody,
path: filePath,
line: 1, // 文件开头
line_type: "new"
});
console.log(`成功为 ${filePath} 发布评论`);
} catch (error) {
console.error(`向 GitLab 发布评论失败 (${filePath}):`, error);
// 如果行内评论失败(例如文件已删除或为二进制文件),则回退到普通评论
try {
await request(url, {
method: "POST",
headers: {
"PRIVATE-TOKEN": GITLAB_TOKEN,
"Content-Type": "application/json"
}
}, {
note: commentBody
});
console.log(`成功为 ${filePath} 发布普通评论`);
} catch (error) {
console.error("发布普通评论失败:", error);
}
}
}
async function main() {
const changedFiles = getChangedFiles();
if (changedFiles.length === 0) {
console.log("最近一次提交没有文件变更。");
return;
}
const targetExtensions = new Set([".js", ".jsx", ".ts", ".tsx", ".uts", ".uvue", ".vue"]);
const ignorePatterns = [".test.", ".spec.", "node_modules", "dist/", "build/"];
for (const file of changedFiles) {
if (!fs.existsSync(file)) {
console.log(`文件 ${file} 不存在 (可能已删除),跳过。`);
continue;
}
const ext = path.extname(file);
const isTarget = targetExtensions.has(ext);
const shouldIgnore = ignorePatterns.some(pattern => file.includes(pattern));
if (isTarget && !shouldIgnore) {
console.log(`正在处理 ${file}...`);
const content = fs.readFileSync(file, "utf8");
// 限制内容大小以避免超出 Token 限制(估算)
if (content.length > 20_000) {
console.log(`文件 ${file} 太大 (${content.length} 字符),跳过。`);
continue;
}
const testCode = await generateUnitTest(file, content);
if (testCode) {
await postGitLabComment(file, testCode);
}
}
}
}
main().catch(error => {
console.error("未捕获的错误:", error);
process.exit(1);
});
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!