import re import logging import json from pathlib import Path from typing import Optional from agent.llm_client import LLMClient, LLMMessage from agent.code_analyzer import FileAnalysis from agent.domain_extractor import DomainModel from agent.prompt_builder import PromptBuilder logger = logging.getLogger(__name__) class TestGenerator: def __init__(self, llm_client: LLMClient, prompt_builder: PromptBuilder): self.llm = llm_client self.prompt_builder = prompt_builder def generate_tests_for_file( self, file_analysis: FileAnalysis, source_code: str, domain_model: DomainModel, test_type: str = "unit", ) -> dict[str, str]: prompt = self.prompt_builder.build_test_generation_prompt( file_analysis, source_code, domain_model, test_type ) system_prompt = self.prompt_builder.build_system_prompt(domain_model) messages = [LLMMessage(role="user", content=prompt)] response = self.llm.chat(messages, system_prompt=system_prompt) return self._parse_generated_tests(response.content) def generate_tests_for_context( self, context_name: str, analyses: list[FileAnalysis], source_codes: dict[str, str], domain_model: DomainModel, test_types: list[str] = None, ) -> dict[str, dict[str, str]]: if test_types is None: test_types = ["smoke", "unit", "integration"] all_results = {} for analysis in analyses: source = source_codes.get(analysis.path, "") for test_type in test_types: key = f"{analysis.path}::{test_type}" results = self.generate_tests_for_file( analysis, source, domain_model, test_type ) all_results[key] = results return all_results def generate_tests_for_all( self, analyses: list[FileAnalysis], source_codes: dict[str, str], domain_model: DomainModel, test_types: list[str] = None, ) -> dict[str, dict[str, str]]: if test_types is None: test_types = ["smoke", "unit", "integration"] all_results = {} for i, analysis in enumerate(analyses): if analysis.line_count == 0: continue if any(pat in analysis.path for pat in ("__init__.py", "setup.py", "conftest.py")): continue source = source_codes.get(analysis.path, "") logger.info(f"[{i+1}/{len(analyses)}] 生成测试: {analysis.path}") for test_type in test_types: key = f"{analysis.path}::{test_type}" results = self.generate_tests_for_file( analysis, source, domain_model, test_type ) all_results[key] = results return all_results def _parse_generated_tests(self, content: str) -> dict[str, str]: results = {} pattern = re.compile( r'```python\s*\n(?:#\s*(tests/[^\n]+)\s*\n)?(.*?)(?:```|$)', re.DOTALL, ) for match in pattern.finditer(content): file_path = match.group(1) code = match.group(2) if file_path: file_path = file_path.strip() else: file_path = "test_generated.py" results[file_path] = code.strip() if not results: code_blocks = re.findall(r'```python\s*\n(.*?)(?:```|$)', content, re.DOTALL) for i, code in enumerate(code_blocks): if code.strip(): results[f"test_generated_{i+1}.py"] = code.strip() return results def write_tests( self, generated: dict[str, dict[str, str]], output_dir: Path, domain_model: DomainModel, ) -> list[Path]: output_dir = Path(output_dir) output_dir.mkdir(parents=True, exist_ok=True) written_files = [] for key, test_files in generated.items(): for file_path, code in test_files.items(): if not code.strip(): continue parts = file_path.split("/") context_name = parts[1] if len(parts) > 2 else "shared_kernel" full_path = output_dir / file_path full_path.parent.mkdir(parents=True, exist_ok=True) full_path.write_text(code, encoding="utf-8") logger.info(f"写入测试文件: {full_path}") written_files.append(full_path) self._write_conftest(output_dir, domain_model) written_files.append(output_dir / "conftest.py") self._write_domain_report(output_dir, domain_model) written_files.append(output_dir / "domain_report.md") return written_files def _write_conftest(self, output_dir: Path, domain_model: DomainModel): markers = set() for ctx in domain_model.bounded_contexts: markers.add(ctx.name) conftest = [ '"""DDD 测试框架 conftest - 按限界上下文组织"""', "import pytest", "", ] for marker in sorted(markers): conftest.append(f'pytest_plugins.append("{marker}")') conftest.append("") conftest.append(""" @pytest.fixture(scope="session") def domain_model(): \"\"\"提供领域模型作为测试 fixture\"\"\" return {} @pytest.fixture def mock_repository(mocker): \"\"\"Mock 仓储层,隔离基础设施依赖\"\"\" def _mock(repo_class): return mocker.patch(f"{repo_class}.__init__", return_value=None) return _mock @pytest.fixture def mock_external_service(mocker): \"\"\"Mock 外部服务调用\"\"\" def _mock(service_path, return_value=None): return mocker.patch(service_path, return_value=return_value) return _mock def pytest_collection_modifyitems(config, items): for item in items: if "domain" in str(item.fspath): item.add_marker(pytest.mark.domain) elif "infrastructure" in str(item.fspath): item.add_marker(pytest.mark.infrastructure) """) conftest_path = output_dir / "conftest.py" conftest_path.write_text("\n".join(conftest), encoding="utf-8") def _write_domain_report(self, output_dir: Path, domain_model: DomainModel): from agent.domain_extractor import DomainExtractor extractor = DomainExtractor(Path(".")) report = extractor.generate_context_report(domain_model) report_path = output_dir / "domain_report.md" report_path.write_text(report, encoding="utf-8")