TBC/agent/app.py
jiawei.chen 6f6053ff51 feat: TestAgent 智能测试平台 v1.0
- CLI + Web 双平台,基于 LLM 的 TDD+DDD 自动化测试生成
- 集成 unified-test-platform 903 个 D-Cloud 用例 + 13 个 Robogo 场景
- Agent 5 步流水线: 扫描 -> DDD -> LLM 生成测试
- 精确回归 + UI 变更检查
- 可视化 HTML 测试报告
- 暗色/亮色主题切换
- 19 个 API 端点 + 6 个 SPA 页面
- 15/15 项 TDD+DDD 合规
2026-07-08 11:27:38 +08:00

196 lines
7.5 KiB
Python

import os
import logging
from pathlib import Path
from typing import Optional
import yaml
from agent.llm_client import LLMClient, LLMConfig
from agent.git_ops import GitOps, GitRepoInfo
from agent.code_analyzer import CodeAnalyzer, FileAnalysis
from agent.domain_extractor import DomainExtractor, DomainModel
from agent.prompt_builder import PromptBuilder
from agent.test_generator import TestGenerator
logger = logging.getLogger(__name__)
class TestAgent:
def __init__(self, config_path: str = "config.yaml"):
self.config = self._load_config(config_path)
self._setup_logging()
self.llm_config = LLMConfig(
provider=self.config.get("agent", {}).get("provider", "deepseek"),
model=self.config.get("agent", {}).get("model", "deepseek-chat"),
base_url=self.config.get("agent", {}).get("base_url", "https://api.deepseek.com"),
temperature=self.config.get("agent", {}).get("temperature", 0.3),
max_tokens=self.config.get("agent", {}).get("max_tokens", 8192),
)
self.work_dir = Path(self.config.get("git", {}).get("work_dir", "./work"))
self.output_dir = Path(self.config.get("test_generation", {}).get("output_dir", "tests"))
self.llm_client: Optional[LLMClient] = None
self.git_ops = GitOps(self.work_dir)
self.prompt_builder: Optional[PromptBuilder] = None
self._api_key: str = ""
def _load_config(self, config_path: str) -> dict:
path = Path(config_path)
if path.exists():
with open(path, "r", encoding="utf-8") as f:
return yaml.safe_load(f)
return {}
def _setup_logging(self):
level = getattr(logging, self.config.get("logging", {}).get("level", "INFO").upper(), logging.INFO)
fmt = self.config.get("logging", {}).get("format", "%(asctime)s [%(levelname)s] %(name)s: %(message)s")
logging.basicConfig(level=level, format=fmt)
def set_api_key(self, api_key: str):
self._api_key = api_key
self.llm_config.api_key = api_key
self.llm_client = LLMClient(self.llm_config)
base_dir = Path(__file__).parent.parent
skills_dir = base_dir / "skills"
soul_path = base_dir / "SOUL.md"
self.prompt_builder = PromptBuilder(skills_dir, soul_path)
def run(
self,
repo_url: str,
branch: str = "main",
test_types: list[str] = None,
output_dir: str = None,
) -> dict:
if not self._api_key:
raise ValueError("请先调用 set_api_key(api_key) 设置 API Key")
if test_types is None:
test_types = ["smoke", "unit", "integration"]
if output_dir:
self.output_dir = Path(output_dir)
logger.info(f"=== TestAgent 开始工作 ===")
logger.info(f"仓库: {repo_url}")
logger.info(f"分支: {branch}")
logger.info(f"测试类型: {test_types}")
logger.info(f"[1/5] 拉取代码...")
repo_info = self.git_ops.clone_or_pull(repo_url, branch)
logger.info(f" 语言: {repo_info.language}")
logger.info(f" 框架: {repo_info.framework}")
logger.info(f" 源文件: {len(repo_info.files)} 个")
logger.info(f"[2/5] 分析代码结构...")
analyzer = CodeAnalyzer(repo_info.local_path)
analyses = analyzer.analyze_all(repo_info.files)
logger.info(f" 分析完成: {len(analyses)} 个文件")
class_count = sum(len(a.classes) for a in analyses)
func_count = sum(len(a.functions) for a in analyses)
logger.info(f" 类: {class_count}, 函数: {func_count}")
logger.info(f"[3/5] 提取 DDD 领域模型...")
extractor = DomainExtractor(repo_info.local_path)
domain_model = extractor.extract_domains(analyses)
logger.info(f" 限界上下文: {len(domain_model.bounded_contexts)} 个")
for ctx in domain_model.bounded_contexts:
logger.info(f" - {ctx.name}: {len(ctx.files)} 个文件")
logger.info(f"[4/5] 读取源代码...")
source_codes = {}
for analysis in analyses:
source = self.git_ops.get_file_content(repo_info.local_path, analysis.path)
source_codes[analysis.path] = source
logger.info(f"[5/5] 调用 LLM 生成测试用例...")
generator = TestGenerator(self.llm_client, self.prompt_builder)
all_tests = generator.generate_tests_for_all(
analyses, source_codes, domain_model, test_types
)
test_output_dir = self.output_dir
written_files = generator.write_tests(all_tests, test_output_dir, domain_model)
logger.info(f" 生成测试文件: {len(written_files)} 个")
report = self._build_report(repo_info, analyses, domain_model, written_files, test_types)
return report
def run_diff(
self,
repo_url: str,
branch: str = "main",
against: str = "HEAD~1",
test_types: list[str] = None,
) -> dict:
if not self._api_key:
raise ValueError("请先调用 set_api_key(api_key) 设置 API Key")
if test_types is None:
test_types = ["regression", "unit"]
logger.info(f"=== TestAgent 精确回归模式 ===")
logger.info(f"仓库: {repo_url}")
logger.info(f"对比: {against}")
repo_info = self.git_ops.clone_or_pull(repo_url, branch)
diff_files = self.git_ops.get_diff(repo_info.local_path, against)
if not diff_files:
logger.info("没有检测到代码变更,跳过")
return {"changed_files": [], "generated_tests": []}
logger.info(f"变更文件: {len(diff_files)} 个")
for f in diff_files:
logger.info(f" - {f}")
analyzer = CodeAnalyzer(repo_info.local_path)
analyses = analyzer.analyze_all(diff_files)
extractor = DomainExtractor(repo_info.local_path)
domain_model = extractor.extract_domains(analyses)
source_codes = {}
for analysis in analyses:
source = self.git_ops.get_file_content(repo_info.local_path, analysis.path)
source_codes[analysis.path] = source
generator = TestGenerator(self.llm_client, self.prompt_builder)
all_tests = generator.generate_tests_for_all(
analyses, source_codes, domain_model, test_types
)
written_files = generator.write_tests(all_tests, self.output_dir, domain_model)
return {
"changed_files": diff_files,
"generated_tests": [str(f) for f in written_files],
"domain_contexts": [ctx.name for ctx in domain_model.bounded_contexts],
}
def _build_report(
self,
repo_info: GitRepoInfo,
analyses: list[FileAnalysis],
domain_model: DomainModel,
written_files: list[Path],
test_types: list[str],
) -> dict:
return {
"repo_url": repo_info.url,
"branch": repo_info.branch,
"language": repo_info.language,
"framework": repo_info.framework,
"files_analyzed": len(analyses),
"classes_found": sum(len(a.classes) for a in analyses),
"functions_found": sum(len(a.functions) for a in analyses),
"bounded_contexts": len(domain_model.bounded_contexts),
"context_names": [ctx.name for ctx in domain_model.bounded_contexts],
"test_types": test_types,
"test_files_generated": len(written_files),
"output_dir": str(self.output_dir),
"test_files": [str(f) for f in written_files],
}