包含 CodeAgent 前后端源码、SKILLS、MCP、demo 代码与工作区文档。 排除依赖缓存、运行数据、备份与二进制附件,规则见 .gitignore。 Co-Authored-By: Claude Code <[email protected]>
79 lines
2.3 KiB
Python
79 lines
2.3 KiB
Python
"""
|
||
测试生成服务
|
||
============
|
||
|
||
【功能说明】为指定代码文件/类/方法自动生成单元测试。
|
||
对应功能 25:改码后自动补测试。
|
||
|
||
【技术选型理由】
|
||
1. 强模型 + 代码上下文 → 生成 JUnit/Mockito 测试;
|
||
2. 可指定测试框架和覆盖场景。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import logging
|
||
|
||
from app.models.model_router import get_model_for_task
|
||
|
||
logger = logging.getLogger("agent.testgen")
|
||
|
||
|
||
def generate_tests(
|
||
source_code: str,
|
||
file_name: str = "",
|
||
test_framework: str = "junit5",
|
||
model_preference: str = "auto",
|
||
) -> dict:
|
||
"""
|
||
为指定代码生成单元测试。
|
||
|
||
【参数】
|
||
source_code:Java 源代码
|
||
file_name:文件名(供生成测试类名)
|
||
test_framework:junit5 / mockito / spring
|
||
model_preference:模型偏好
|
||
"""
|
||
if not source_code.strip():
|
||
return {"success": False, "message": "请提供源代码"}
|
||
|
||
prompt = f"""你是资深 Java 测试工程师。请为下面的代码生成完整的单元测试。
|
||
|
||
【源文件】{file_name or '未命名'}
|
||
【测试框架】{test_framework}
|
||
|
||
【源代码】
|
||
```
|
||
{source_code[:8000]}
|
||
```
|
||
|
||
【要求】
|
||
1. 使用 {test_framework} 框架,测试类命名为 `{{原类名}}Test`
|
||
2. 覆盖:正常场景、边界条件、异常场景
|
||
3. 外部依赖用 Mockito mock
|
||
4. 每个测试方法命名:test_{{方法名}}_{{场景}}
|
||
5. 添加中文注释说明每个测试的意图
|
||
6. 直接输出完整测试代码,用 ```java 包裹"""
|
||
|
||
try:
|
||
model = get_model_for_task(model_preference, "strong")
|
||
model_name = getattr(model, "model_name", None) or getattr(model, "model", "")
|
||
resp = model.invoke(prompt)
|
||
output = resp.content if hasattr(resp, "content") else str(resp)
|
||
|
||
# 提取代码块
|
||
import re
|
||
|
||
code_match = re.search(r"```java\s*\n(.*?)\n```", output, re.DOTALL)
|
||
test_code = code_match.group(1) if code_match else output
|
||
|
||
return {
|
||
"success": True,
|
||
"test_code": test_code,
|
||
"model": model_name,
|
||
"file_name": file_name,
|
||
}
|
||
except Exception as exc: # noqa: BLE001
|
||
logger.exception("测试生成失败")
|
||
return {"success": False, "message": f"测试生成失败:{exc}"}
|