- 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 合规
218 lines
7.8 KiB
Python
218 lines
7.8 KiB
Python
#!/usr/bin/env python3
|
||
"""TestAgent - 基于 LLM 的 TDD+DDD 自动化测试用例生成器
|
||
|
||
用法:
|
||
python main.py run --repo <git-url> --api-key <key>
|
||
python main.py run --repo <git-url> --api-key <key> --branch main --types smoke,unit,integration
|
||
python main.py diff --repo <git-url> --api-key <key> --against HEAD~3
|
||
python main.py analyze --repo <git-url> --api-key <key>
|
||
"""
|
||
|
||
import sys
|
||
import os
|
||
from pathlib import Path
|
||
from typing import Optional
|
||
|
||
import click
|
||
from rich.console import Console
|
||
from rich.table import Table
|
||
from rich.panel import Panel
|
||
from rich.progress import Progress, SpinnerColumn, TextColumn
|
||
from rich.markdown import Markdown
|
||
|
||
from agent.app import TestAgent
|
||
|
||
console = Console()
|
||
|
||
|
||
def get_api_key(api_key: Optional[str]) -> str:
|
||
if api_key:
|
||
return api_key
|
||
|
||
from dotenv import load_dotenv
|
||
load_dotenv()
|
||
|
||
env_key = os.getenv("DEEPSEEK_API_KEY") or os.getenv("OPENAI_API_KEY")
|
||
if env_key:
|
||
return env_key
|
||
|
||
return click.prompt("请输入 API Key", hide_input=True, type=str)
|
||
|
||
|
||
@click.group()
|
||
@click.version_option(version="1.0.0")
|
||
def cli():
|
||
"""TestAgent - 智能测试用例生成器
|
||
|
||
基于 LLM 自动扫描 Git 仓库,按 TDD+DDD 规范生成测试用例。
|
||
"""
|
||
|
||
|
||
@cli.command()
|
||
@click.option("--repo", "-r", required=True, help="Git 仓库地址")
|
||
@click.option("--api-key", "-k", default=None, help="LLM API Key(不提供则交互式输入)")
|
||
@click.option("--branch", "-b", default="main", help="分支名称")
|
||
@click.option("--types", "-t", default="smoke,unit,integration", help="测试类型,逗号分隔")
|
||
@click.option("--output", "-o", default="tests", help="测试输出目录")
|
||
@click.option("--config", "-c", default="config.yaml", help="配置文件路径")
|
||
def run(repo, api_key, branch, types, output, config):
|
||
"""扫描仓库并生成测试用例"""
|
||
api_key = get_api_key(api_key)
|
||
test_types = [t.strip() for t in types.split(",")]
|
||
|
||
agent = TestAgent(config_path=config)
|
||
agent.set_api_key(api_key)
|
||
agent.output_dir = Path(output)
|
||
|
||
with Progress(
|
||
SpinnerColumn(),
|
||
TextColumn("[progress.description]{task.description}"),
|
||
console=console,
|
||
) as progress:
|
||
task = progress.add_task("[cyan]TestAgent 工作中...", total=None)
|
||
try:
|
||
report = agent.run(
|
||
repo_url=repo,
|
||
branch=branch,
|
||
test_types=test_types,
|
||
output_dir=output,
|
||
)
|
||
except Exception as e:
|
||
console.print(f"\n[red]错误: {e}[/red]")
|
||
sys.exit(1)
|
||
progress.remove_task(task)
|
||
|
||
_print_report(report)
|
||
|
||
|
||
@cli.command()
|
||
@click.option("--repo", "-r", required=True, help="Git 仓库地址")
|
||
@click.option("--api-key", "-k", default=None, help="LLM API Key")
|
||
@click.option("--branch", "-b", default="main", help="分支名称")
|
||
@click.option("--against", "-a", default="HEAD~1", help="对比的基准")
|
||
@click.option("--types", "-t", default="regression,unit", help="测试类型")
|
||
@click.option("--output", "-o", default="tests", help="测试输出目录")
|
||
@click.option("--config", "-c", default="config.yaml", help="配置文件路径")
|
||
def diff(repo, api_key, branch, against, types, output, config):
|
||
"""精确回归模式:只对变更代码生成测试"""
|
||
api_key = get_api_key(api_key)
|
||
test_types = [t.strip() for t in types.split(",")]
|
||
|
||
agent = TestAgent(config_path=config)
|
||
agent.set_api_key(api_key)
|
||
agent.output_dir = Path(output)
|
||
|
||
with Progress(
|
||
SpinnerColumn(),
|
||
TextColumn("[progress.description]{task.description}"),
|
||
console=console,
|
||
) as progress:
|
||
task = progress.add_task("[cyan]精确回归分析中...", total=None)
|
||
try:
|
||
report = agent.run_diff(
|
||
repo_url=repo,
|
||
branch=branch,
|
||
against=against,
|
||
test_types=test_types,
|
||
)
|
||
except Exception as e:
|
||
console.print(f"\n[red]错误: {e}[/red]")
|
||
sys.exit(1)
|
||
progress.remove_task(task)
|
||
|
||
_print_diff_report(report)
|
||
|
||
|
||
@cli.command()
|
||
@click.option("--repo", "-r", required=True, help="Git 仓库地址")
|
||
@click.option("--api-key", "-k", default=None, help="LLM API Key")
|
||
@click.option("--branch", "-b", default="main", help="分支名称")
|
||
@click.option("--config", "-c", default="config.yaml", help="配置文件路径")
|
||
def analyze(repo, api_key, branch, config):
|
||
"""只分析代码结构和 DDD 领域模型,不生成测试"""
|
||
api_key = get_api_key(api_key)
|
||
|
||
agent = TestAgent(config_path=config)
|
||
agent.set_api_key(api_key)
|
||
|
||
console.print("[cyan]拉取代码...[/cyan]")
|
||
repo_info = agent.git_ops.clone_or_pull(repo, branch)
|
||
|
||
from agent.code_analyzer import CodeAnalyzer
|
||
from agent.domain_extractor import DomainExtractor
|
||
|
||
console.print("[cyan]分析代码结构...[/cyan]")
|
||
analyzer = CodeAnalyzer(repo_info.local_path)
|
||
analyses = analyzer.analyze_all(repo_info.files)
|
||
|
||
console.print("[cyan]提取 DDD 领域模型...[/cyan]")
|
||
extractor = DomainExtractor(repo_info.local_path)
|
||
domain_model = extractor.extract_domains(analyses)
|
||
|
||
table = Table(title=f"DDD 领域分析 - {repo_info.language}/{repo_info.framework}")
|
||
table.add_column("限界上下文", style="cyan")
|
||
table.add_column("文件数", style="green")
|
||
table.add_column("聚合根", style="yellow")
|
||
table.add_column("领域服务", style="magenta")
|
||
table.add_column("实体", style="blue")
|
||
|
||
for ctx in domain_model.bounded_contexts:
|
||
table.add_row(
|
||
ctx.name,
|
||
str(len(ctx.files)),
|
||
", ".join(ctx.aggregate_roots[:3]) or "-",
|
||
", ".join(ctx.domain_services[:3]) or "-",
|
||
", ".join(ctx.entities[:3]) or "-",
|
||
)
|
||
|
||
console.print(table)
|
||
console.print(f"\n[green]总文件数: {len(repo_info.files)}[/green]")
|
||
console.print(f"[green]分析文件数: {len(analyses)}[/green]")
|
||
console.print(f"[green]限界上下文: {len(domain_model.bounded_contexts)}[/green]")
|
||
|
||
|
||
def _print_report(report: dict):
|
||
console.print("\n")
|
||
console.print(Panel.fit("✅ TestAgent 工作完成", style="green bold"))
|
||
|
||
table = Table(title="生成报告")
|
||
table.add_column("项目", style="cyan")
|
||
table.add_column("值", style="green")
|
||
|
||
table.add_row("仓库", report.get("repo_url", "-"))
|
||
table.add_row("语言/框架", f"{report.get('language', '-')}/{report.get('framework', '-')}")
|
||
table.add_row("分析文件数", str(report.get("files_analyzed", 0)))
|
||
table.add_row("发现类/函数", f"{report.get('classes_found', 0)}/{report.get('functions_found', 0)}")
|
||
table.add_row("限界上下文", ", ".join(report.get("context_names", [])))
|
||
table.add_row("测试类型", ", ".join(report.get("test_types", [])))
|
||
table.add_row("生成测试文件", str(report.get("test_files_generated", 0)))
|
||
table.add_row("输出目录", report.get("output_dir", "-"))
|
||
|
||
console.print(table)
|
||
|
||
if report.get("test_files"):
|
||
console.print("\n[bold]生成的测试文件:[/bold]")
|
||
for f in report["test_files"]:
|
||
console.print(f" [cyan]📄 {f}[/cyan]")
|
||
|
||
|
||
def _print_diff_report(report: dict):
|
||
console.print("\n")
|
||
console.print(Panel.fit("✅ 精确回归分析完成", style="green bold"))
|
||
|
||
console.print(f"\n[bold]变更文件 ({len(report.get('changed_files', []))} 个):[/bold]")
|
||
for f in report.get("changed_files", []):
|
||
console.print(f" [yellow]{f}[/yellow]")
|
||
|
||
console.print(f"\n[bold]涉及限界上下文:[/bold]")
|
||
for ctx in report.get("domain_contexts", []):
|
||
console.print(f" [cyan]{ctx}[/cyan]")
|
||
|
||
if report.get("generated_tests"):
|
||
console.print(f"\n[bold]生成的回归测试:[/bold]")
|
||
for f in report["generated_tests"]:
|
||
console.print(f" [green]📄 {f}[/green]")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
cli() |