fix: Semantic coverage mapping + real mutation execution + syntax validation
Browse files
backend/app/services/multi_agent_engine.py
CHANGED
|
@@ -1,31 +1,30 @@
|
|
| 1 |
"""
|
| 2 |
-
TestGenius AI β Multi-Agent Iterative Test Refinement Engine
|
| 3 |
-
==============================================================
|
| 4 |
-
RESEARCH-GRADE
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
"""
|
| 22 |
|
| 23 |
import re
|
| 24 |
import ast
|
| 25 |
-
import json
|
| 26 |
import time
|
| 27 |
import uuid
|
| 28 |
-
from typing import Dict, List, Any, Optional
|
| 29 |
from dataclasses import dataclass, field
|
| 30 |
|
| 31 |
from app.services.llm_provider import generate_with_llm
|
|
@@ -34,11 +33,12 @@ from app.services.novelty_features import (
|
|
| 34 |
detect_coverage_gaps,
|
| 35 |
score_test_quality,
|
| 36 |
suggest_mutations,
|
|
|
|
| 37 |
)
|
| 38 |
|
| 39 |
|
| 40 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 41 |
-
# BEHAVIOR EXTRACTION (Qodo/CodiumAI-style)
|
| 42 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 43 |
|
| 44 |
@dataclass
|
|
@@ -48,88 +48,475 @@ class Behavior:
|
|
| 48 |
description: str
|
| 49 |
category: str # "happy_path" | "edge_case" | "error_handling" | "security" | "performance"
|
| 50 |
priority: str # "critical" | "high" | "medium" | "low"
|
| 51 |
-
source: str
|
|
|
|
| 52 |
tested: bool = False
|
| 53 |
test_ids: List[str] = field(default_factory=list)
|
| 54 |
|
| 55 |
|
| 56 |
def extract_behaviors(source_code: str = "", requirements: str = "", api_spec: dict = None) -> List[Behavior]:
|
| 57 |
"""
|
| 58 |
-
Extract ALL testable behaviors
|
| 59 |
-
|
| 60 |
"""
|
| 61 |
behaviors = []
|
| 62 |
bid = 0
|
| 63 |
|
| 64 |
-
# From source code: extract function behaviors
|
| 65 |
if source_code:
|
| 66 |
try:
|
| 67 |
tree = ast.parse(source_code)
|
| 68 |
for node in ast.walk(tree):
|
| 69 |
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
| 70 |
fname = node.name
|
|
|
|
|
|
|
|
|
|
| 71 |
params = [a.arg for a in node.args.args if a.arg != 'self']
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
|
| 73 |
# Happy path
|
| 74 |
-
behaviors.append(Behavior(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
bid += 1
|
| 76 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
# Edge cases per param
|
| 78 |
for p in params:
|
| 79 |
-
behaviors.append(Behavior(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
bid += 1
|
| 81 |
-
behaviors.append(Behavior(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
bid += 1
|
| 83 |
|
| 84 |
-
# Error paths
|
| 85 |
-
for child in ast.walk(node):
|
| 86 |
-
if isinstance(child, ast.Raise):
|
| 87 |
-
behaviors.append(Behavior(id=f"B{bid:03d}", description=f"{fname}() raises exception on invalid input", category="error_handling", priority="high", source=f"function:{fname}"))
|
| 88 |
-
bid += 1
|
| 89 |
-
break
|
| 90 |
-
|
| 91 |
-
# Return None path
|
| 92 |
-
for child in ast.walk(node):
|
| 93 |
-
if isinstance(child, ast.Return) and child.value is None:
|
| 94 |
-
behaviors.append(Behavior(id=f"B{bid:03d}", description=f"{fname}() can return None β verify handling", category="edge_case", priority="medium", source=f"function:{fname}"))
|
| 95 |
-
bid += 1
|
| 96 |
-
break
|
| 97 |
except SyntaxError:
|
| 98 |
pass
|
| 99 |
|
| 100 |
-
# From requirements
|
| 101 |
if requirements:
|
| 102 |
-
sentences = re.split(r'[.\nβ’\-]', requirements)
|
| 103 |
for sent in sentences:
|
| 104 |
sent = sent.strip()
|
| 105 |
-
if len(sent)
|
| 106 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
bid += 1
|
| 108 |
-
if any(kw in sent.lower() for kw in ['
|
| 109 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
bid += 1
|
| 111 |
|
| 112 |
-
# From API spec
|
| 113 |
if api_spec:
|
| 114 |
for path, methods in api_spec.get("paths", {}).items():
|
| 115 |
for method, details in methods.items():
|
| 116 |
if method not in ("get", "post", "put", "patch", "delete"):
|
| 117 |
continue
|
| 118 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
bid += 1
|
| 120 |
-
behaviors.append(Behavior(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
bid += 1
|
| 122 |
-
behaviors.append(Behavior(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
bid += 1
|
| 124 |
-
if method in ("post", "put"):
|
| 125 |
-
behaviors.append(Behavior(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
bid += 1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
|
| 128 |
return behaviors
|
| 129 |
|
| 130 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 132 |
-
# MULTI-AGENT ITERATIVE REFINEMENT ENGINE
|
| 133 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 134 |
|
| 135 |
async def run_multi_agent_pipeline(
|
|
@@ -139,23 +526,16 @@ async def run_multi_agent_pipeline(
|
|
| 139 |
framework: str = "pytest",
|
| 140 |
language: str = "python",
|
| 141 |
test_types: List[str] = None,
|
| 142 |
-
max_iterations: int =
|
| 143 |
) -> Dict[str, Any]:
|
| 144 |
"""
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
Pipeline:
|
| 148 |
-
1. ANALYZE β Extract behaviors + complexity + gaps
|
| 149 |
-
2. GENERATE β Initial test generation (LLM)
|
| 150 |
-
3. VALIDATE β Score quality, find weaknesses
|
| 151 |
-
4. REFINE β Use mutation info to strengthen weak tests (iterate)
|
| 152 |
-
5. MAP COVERAGE β Show which behaviors are tested vs untested
|
| 153 |
-
|
| 154 |
-
Returns comprehensive result with behavior coverage map.
|
| 155 |
"""
|
| 156 |
start_time = time.time()
|
| 157 |
run_id = f"MAS-{uuid.uuid4().hex[:8]}"
|
| 158 |
test_types = test_types or ["unit", "integration", "edge_case", "security"]
|
|
|
|
| 159 |
|
| 160 |
# βββ AGENT 1: ANALYZER βββ
|
| 161 |
analysis = {
|
|
@@ -164,103 +544,127 @@ async def run_multi_agent_pipeline(
|
|
| 164 |
"gaps": detect_coverage_gaps(source_code) if source_code else None,
|
| 165 |
}
|
| 166 |
|
| 167 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
input_context = _build_rich_context(source_code, requirements, api_spec, analysis)
|
| 169 |
-
|
| 170 |
-
system_prompt = """You are TestGenius, an expert QA automation engineer.
|
| 171 |
-
Generate COMPREHENSIVE, RUNNABLE test code. Include ALL imports.
|
| 172 |
-
Use descriptive test names: test_<what>_<scenario>_<expected>.
|
| 173 |
-
Cover: happy path, edge cases (null/empty/boundary), errors, security.
|
| 174 |
-
Generate 15-25 test functions. Add docstrings per test.
|
| 175 |
-
Output ONLY code in a single code block."""
|
| 176 |
|
| 177 |
gen_prompt = f"""Generate {framework} tests in {language}.
|
| 178 |
Test types: {', '.join(test_types)}
|
|
|
|
| 179 |
|
| 180 |
CONTEXT:
|
| 181 |
{input_context}
|
| 182 |
|
| 183 |
BEHAVIORS TO TEST ({len(analysis['behaviors'])} identified):
|
| 184 |
-
{chr(10).join(f'- [{b.priority.upper()}] {b.description}' for b in analysis['behaviors'][:
|
|
|
|
|
|
|
| 185 |
|
| 186 |
Generate the complete test file now:"""
|
| 187 |
|
| 188 |
raw_tests = await generate_with_llm(gen_prompt, system_prompt, temperature=0.3)
|
| 189 |
|
| 190 |
-
# βββ AGENT 3: VALIDATOR
|
|
|
|
| 191 |
quality_score = score_test_quality(raw_tests)
|
| 192 |
-
mutations = suggest_mutations(source_code) if source_code else {"mutations": [], "total_mutations": 0}
|
| 193 |
|
| 194 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 195 |
refined_tests = raw_tests
|
| 196 |
refinement_history = []
|
|
|
|
| 197 |
|
| 198 |
for iteration in range(max_iterations):
|
| 199 |
-
if quality_score["overall"] >=
|
| 200 |
-
break
|
| 201 |
-
|
| 202 |
-
#
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
weak_areas.append("Add more error handling tests: invalid types, missing fields, auth failures")
|
| 208 |
-
if quality_score["scores"].get("assertions", 0) < 6:
|
| 209 |
-
weak_areas.append("Strengthen assertions: check more conditions per test, verify side effects")
|
| 210 |
-
|
| 211 |
-
if mutations["total_mutations"] > 0:
|
| 212 |
-
surviving = mutations["mutations"][:5]
|
| 213 |
-
mutation_context = "\n".join(f"- Line {m['line']}: {m['mutant']}" for m in surviving)
|
| 214 |
-
weak_areas.append(f"These mutations would SURVIVE your tests (add tests to catch them):\n{mutation_context}")
|
| 215 |
|
|
|
|
| 216 |
if not weak_areas:
|
| 217 |
break
|
| 218 |
|
| 219 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 220 |
|
| 221 |
-
|
|
|
|
|
|
|
| 222 |
{chr(10).join(f'{i+1}. {w}' for i, w in enumerate(weak_areas))}
|
|
|
|
| 223 |
|
| 224 |
CURRENT TESTS:
|
| 225 |
```
|
| 226 |
-
{refined_tests[:
|
| 227 |
```
|
| 228 |
|
| 229 |
-
|
| 230 |
|
| 231 |
refined_tests = await generate_with_llm(refine_prompt, system_prompt, temperature=0.2)
|
| 232 |
-
|
|
|
|
|
|
|
| 233 |
refinement_history.append({
|
| 234 |
"iteration": iteration + 1,
|
| 235 |
"quality_before": quality_score["overall"],
|
|
|
|
| 236 |
"weaknesses_addressed": weak_areas,
|
|
|
|
|
|
|
| 237 |
})
|
|
|
|
| 238 |
|
| 239 |
-
# βββ AGENT 5: COVERAGE MAPPER
|
| 240 |
-
behavior_coverage =
|
| 241 |
|
| 242 |
-
|
| 243 |
processing_time = (time.time() - start_time) * 1000
|
| 244 |
|
| 245 |
return {
|
| 246 |
"run_id": run_id,
|
| 247 |
-
"pipeline": "multi-agent-iterative",
|
| 248 |
"status": "completed",
|
| 249 |
"timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ"),
|
| 250 |
-
|
| 251 |
-
# Generated tests
|
| 252 |
"test_code": refined_tests,
|
| 253 |
"test_files": _parse_to_files(refined_tests, framework, language),
|
| 254 |
-
|
| 255 |
-
# Quality metrics
|
| 256 |
"quality": quality_score,
|
| 257 |
"iterations_performed": len(refinement_history),
|
| 258 |
"refinement_history": refinement_history,
|
| 259 |
-
|
| 260 |
-
# Behavior coverage (NOVELTY)
|
| 261 |
"behavior_coverage": behavior_coverage,
|
| 262 |
-
|
| 263 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 264 |
"analysis": {
|
| 265 |
"total_behaviors": len(analysis["behaviors"]),
|
| 266 |
"behaviors_tested": behavior_coverage["covered"],
|
|
@@ -268,9 +672,7 @@ Generate an IMPROVED version with the weaknesses fixed. Keep all existing good t
|
|
| 268 |
"coverage_pct": behavior_coverage["coverage_pct"],
|
| 269 |
"complexity": analysis.get("complexity"),
|
| 270 |
"gaps": analysis.get("gaps"),
|
| 271 |
-
"mutations": mutations,
|
| 272 |
},
|
| 273 |
-
|
| 274 |
"processing_time_ms": round(processing_time, 1),
|
| 275 |
}
|
| 276 |
|
|
@@ -279,79 +681,135 @@ Generate an IMPROVED version with the weaknesses fixed. Keep all existing good t
|
|
| 279 |
# HELPERS
|
| 280 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 281 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 282 |
def _build_rich_context(code: str, reqs: str, api: dict, analysis: dict) -> str:
|
| 283 |
-
"""Build rich context string for LLM prompt."""
|
| 284 |
parts = []
|
| 285 |
if code:
|
| 286 |
-
parts.append(f"SOURCE CODE:\n```\n{code[:
|
| 287 |
if analysis.get("complexity"):
|
| 288 |
c = analysis["complexity"]
|
| 289 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 290 |
if reqs:
|
| 291 |
-
parts.append(f"REQUIREMENTS:\n{reqs[:
|
| 292 |
if api:
|
| 293 |
endpoints = []
|
| 294 |
for path, methods in api.get("paths", {}).items():
|
| 295 |
for method in methods:
|
| 296 |
-
if method in ("get","post","put","patch","delete"):
|
| 297 |
endpoints.append(f" {method.upper()} {path}")
|
| 298 |
-
parts.append(f"API ENDPOINTS:\n{chr(10).join(endpoints[:
|
| 299 |
return "\n\n".join(parts)
|
| 300 |
|
| 301 |
|
| 302 |
-
def
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 331 |
|
| 332 |
|
| 333 |
def _parse_to_files(raw: str, framework: str, language: str) -> List[Dict]:
|
| 334 |
-
"""Parse raw LLM output into structured test files."""
|
| 335 |
files = []
|
| 336 |
code_blocks = re.findall(r'```(?:\w+)?\s*(.*?)```', raw, re.DOTALL)
|
| 337 |
-
|
| 338 |
if code_blocks:
|
| 339 |
for i, block in enumerate(code_blocks):
|
| 340 |
-
|
|
|
|
|
|
|
|
|
|
| 341 |
files.append({
|
| 342 |
-
"filename": f"test_generated_{i+1}{ext}",
|
| 343 |
-
"framework": framework,
|
| 344 |
-
"language": language,
|
| 345 |
-
"code": block.strip(),
|
| 346 |
"num_tests": block.count("def test_") + block.count("it(") + block.count("test("),
|
| 347 |
})
|
| 348 |
else:
|
| 349 |
ext = ".py" if language == "python" else ".js"
|
| 350 |
files.append({
|
| 351 |
"filename": f"test_generated{ext}",
|
| 352 |
-
"framework": framework,
|
| 353 |
-
"language": language,
|
| 354 |
-
"code": raw,
|
| 355 |
"num_tests": raw.count("def test_") + raw.count("it(") + raw.count("test("),
|
| 356 |
})
|
| 357 |
|
|
|
|
| 1 |
"""
|
| 2 |
+
TestGenius AI β Multi-Agent Iterative Test Refinement Engine (v2 β ALL FIXES)
|
| 3 |
+
===============================================================================
|
| 4 |
+
RESEARCH-GRADE: Based on MuTAP (arxiv:2308.16557) + HITS (ASE 2024) + Code Agents (arxiv:2406.12952)
|
| 5 |
+
|
| 6 |
+
FIXES APPLIED (v2):
|
| 7 |
+
1. β
SEMANTIC coverage mapping (AST-based, not keyword matching)
|
| 8 |
+
2. β
REAL mutation execution β mutates code, runs tests, identifies SURVIVORS
|
| 9 |
+
3. β
Better iteration: max_iterations=5, adaptive threshold, quality improves each pass
|
| 10 |
+
4. β
Test syntax validation β actually compiles/parses generated tests
|
| 11 |
+
5. β
Adaptive prompting β uses complexity analysis to calibrate generation
|
| 12 |
+
6. β
Few-shot examples in refinement prompts for higher quality
|
| 13 |
+
7. β
Execution-verified output β tests are validated to parse before returning
|
| 14 |
+
|
| 15 |
+
Pipeline (iterative until Grade A):
|
| 16 |
+
AGENT 1: Analyzer β AST complexity + behavior extraction + gap detection
|
| 17 |
+
AGENT 2: Generator β Adaptive, context-rich, few-shot LLM generation
|
| 18 |
+
AGENT 3: Validator β Syntax check + execution + quality scoring
|
| 19 |
+
AGENT 4: Refiner β Mutation EXECUTION feedback β re-prompt for stronger tests
|
| 20 |
+
AGENT 5: Coverage Mapper β AST-based semantic behavior coverage
|
| 21 |
"""
|
| 22 |
|
| 23 |
import re
|
| 24 |
import ast
|
|
|
|
| 25 |
import time
|
| 26 |
import uuid
|
| 27 |
+
from typing import Dict, List, Any, Optional, Set
|
| 28 |
from dataclasses import dataclass, field
|
| 29 |
|
| 30 |
from app.services.llm_provider import generate_with_llm
|
|
|
|
| 33 |
detect_coverage_gaps,
|
| 34 |
score_test_quality,
|
| 35 |
suggest_mutations,
|
| 36 |
+
execute_mutations,
|
| 37 |
)
|
| 38 |
|
| 39 |
|
| 40 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 41 |
+
# BEHAVIOR EXTRACTION (AST-based, Qodo/CodiumAI-style)
|
| 42 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 43 |
|
| 44 |
@dataclass
|
|
|
|
| 48 |
description: str
|
| 49 |
category: str # "happy_path" | "edge_case" | "error_handling" | "security" | "performance"
|
| 50 |
priority: str # "critical" | "high" | "medium" | "low"
|
| 51 |
+
source: str
|
| 52 |
+
keywords: List[str] = field(default_factory=list)
|
| 53 |
tested: bool = False
|
| 54 |
test_ids: List[str] = field(default_factory=list)
|
| 55 |
|
| 56 |
|
| 57 |
def extract_behaviors(source_code: str = "", requirements: str = "", api_spec: dict = None) -> List[Behavior]:
|
| 58 |
"""
|
| 59 |
+
Extract ALL testable behaviors using deep AST analysis + NLP heuristics.
|
| 60 |
+
Each behavior gets semantic keywords for accurate coverage mapping.
|
| 61 |
"""
|
| 62 |
behaviors = []
|
| 63 |
bid = 0
|
| 64 |
|
|
|
|
| 65 |
if source_code:
|
| 66 |
try:
|
| 67 |
tree = ast.parse(source_code)
|
| 68 |
for node in ast.walk(tree):
|
| 69 |
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
| 70 |
fname = node.name
|
| 71 |
+
if fname.startswith('_') and fname != '__init__':
|
| 72 |
+
continue
|
| 73 |
+
|
| 74 |
params = [a.arg for a in node.args.args if a.arg != 'self']
|
| 75 |
+
has_return = any(isinstance(n, ast.Return) and n.value is not None for n in ast.walk(node))
|
| 76 |
+
raises = [_get_exception_name(n) for n in ast.walk(node) if isinstance(n, ast.Raise)]
|
| 77 |
+
has_loop = any(isinstance(n, (ast.For, ast.While)) for n in ast.walk(node))
|
| 78 |
+
conditionals = sum(1 for n in ast.walk(node) if isinstance(n, ast.If))
|
| 79 |
+
external_calls = _find_external_calls(node)
|
| 80 |
|
| 81 |
# Happy path
|
| 82 |
+
behaviors.append(Behavior(
|
| 83 |
+
id=f"B{bid:03d}",
|
| 84 |
+
description=f"{fname}() returns correct result with valid inputs ({', '.join(params[:4])})",
|
| 85 |
+
category="happy_path", priority="critical", source=f"function:{fname}",
|
| 86 |
+
keywords=[fname, "valid", "correct", "success"] + params[:3]
|
| 87 |
+
))
|
| 88 |
bid += 1
|
| 89 |
|
| 90 |
+
# Return value type
|
| 91 |
+
if has_return:
|
| 92 |
+
behaviors.append(Behavior(
|
| 93 |
+
id=f"B{bid:03d}",
|
| 94 |
+
description=f"{fname}() return value has correct type and structure",
|
| 95 |
+
category="happy_path", priority="high", source=f"function:{fname}",
|
| 96 |
+
keywords=[fname, "return", "type", "result"]
|
| 97 |
+
))
|
| 98 |
+
bid += 1
|
| 99 |
+
|
| 100 |
# Edge cases per param
|
| 101 |
for p in params:
|
| 102 |
+
behaviors.append(Behavior(
|
| 103 |
+
id=f"B{bid:03d}",
|
| 104 |
+
description=f"{fname}() handles None/null for parameter '{p}'",
|
| 105 |
+
category="edge_case", priority="high", source=f"function:{fname}",
|
| 106 |
+
keywords=[fname, p, "none", "null", "missing"]
|
| 107 |
+
))
|
| 108 |
bid += 1
|
| 109 |
+
behaviors.append(Behavior(
|
| 110 |
+
id=f"B{bid:03d}",
|
| 111 |
+
description=f"{fname}() handles empty/zero value for '{p}'",
|
| 112 |
+
category="edge_case", priority="medium", source=f"function:{fname}",
|
| 113 |
+
keywords=[fname, p, "empty", "zero", "blank"]
|
| 114 |
+
))
|
| 115 |
+
bid += 1
|
| 116 |
+
|
| 117 |
+
# Boundary values for numeric functions
|
| 118 |
+
if any(kw in fname.lower() for kw in ['calc', 'compute', 'count', 'sum', 'total', 'price', 'amount', 'score']):
|
| 119 |
+
behaviors.append(Behavior(
|
| 120 |
+
id=f"B{bid:03d}",
|
| 121 |
+
description=f"{fname}() handles boundary values (max int, negative, float precision)",
|
| 122 |
+
category="edge_case", priority="high", source=f"function:{fname}",
|
| 123 |
+
keywords=[fname, "boundary", "max", "min", "negative", "overflow"]
|
| 124 |
+
))
|
| 125 |
+
bid += 1
|
| 126 |
+
|
| 127 |
+
# Exception paths
|
| 128 |
+
for exc in set(raises):
|
| 129 |
+
behaviors.append(Behavior(
|
| 130 |
+
id=f"B{bid:03d}",
|
| 131 |
+
description=f"{fname}() raises {exc} on invalid input",
|
| 132 |
+
category="error_handling", priority="high", source=f"function:{fname}",
|
| 133 |
+
keywords=[fname, "raises", exc.lower(), "error", "invalid", "exception"]
|
| 134 |
+
))
|
| 135 |
+
bid += 1
|
| 136 |
+
|
| 137 |
+
# Loop correctness
|
| 138 |
+
if has_loop:
|
| 139 |
+
behaviors.append(Behavior(
|
| 140 |
+
id=f"B{bid:03d}",
|
| 141 |
+
description=f"{fname}() loop handles empty collection and single element",
|
| 142 |
+
category="edge_case", priority="medium", source=f"function:{fname}",
|
| 143 |
+
keywords=[fname, "loop", "empty", "single", "iteration"]
|
| 144 |
+
))
|
| 145 |
+
bid += 1
|
| 146 |
+
|
| 147 |
+
# External call mocking
|
| 148 |
+
for call in external_calls[:3]:
|
| 149 |
+
behaviors.append(Behavior(
|
| 150 |
+
id=f"B{bid:03d}",
|
| 151 |
+
description=f"{fname}() handles {call} failure/timeout gracefully",
|
| 152 |
+
category="error_handling", priority="high", source=f"function:{fname}",
|
| 153 |
+
keywords=[fname, call, "mock", "failure", "timeout", "exception"]
|
| 154 |
+
))
|
| 155 |
+
bid += 1
|
| 156 |
+
|
| 157 |
+
# Branch coverage
|
| 158 |
+
if conditionals >= 2:
|
| 159 |
+
behaviors.append(Behavior(
|
| 160 |
+
id=f"B{bid:03d}",
|
| 161 |
+
description=f"{fname}() all {conditionals} conditional branches produce correct output",
|
| 162 |
+
category="happy_path", priority="high", source=f"function:{fname}",
|
| 163 |
+
keywords=[fname, "branch", "condition", "if", "else"]
|
| 164 |
+
))
|
| 165 |
bid += 1
|
| 166 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
except SyntaxError:
|
| 168 |
pass
|
| 169 |
|
| 170 |
+
# From requirements
|
| 171 |
if requirements:
|
| 172 |
+
sentences = re.split(r'[.\nβ’\-\*]', requirements)
|
| 173 |
for sent in sentences:
|
| 174 |
sent = sent.strip()
|
| 175 |
+
if len(sent) < 15:
|
| 176 |
+
continue
|
| 177 |
+
if any(kw in sent.lower() for kw in ['must', 'should', 'can', 'will', 'allow', 'enable', 'support']):
|
| 178 |
+
keywords = [w.lower() for w in re.findall(r'\b[a-zA-Z]{4,}\b', sent)][:6]
|
| 179 |
+
behaviors.append(Behavior(
|
| 180 |
+
id=f"B{bid:03d}", description=sent[:100],
|
| 181 |
+
category="happy_path", priority="high", source="requirements",
|
| 182 |
+
keywords=keywords
|
| 183 |
+
))
|
| 184 |
+
bid += 1
|
| 185 |
+
if any(kw in sent.lower() for kw in ['error', 'fail', 'invalid', 'reject', 'deny', 'block', 'limit', 'prevent']):
|
| 186 |
+
keywords = [w.lower() for w in re.findall(r'\b[a-zA-Z]{4,}\b', sent)][:6]
|
| 187 |
+
behaviors.append(Behavior(
|
| 188 |
+
id=f"B{bid:03d}", description=f"Negative: {sent[:80]}",
|
| 189 |
+
category="error_handling", priority="high", source="requirements",
|
| 190 |
+
keywords=keywords + ["error", "invalid", "reject"]
|
| 191 |
+
))
|
| 192 |
bid += 1
|
| 193 |
+
if any(kw in sent.lower() for kw in ['auth', 'token', 'permission', 'role', 'encrypt', 'secure', 'inject']):
|
| 194 |
+
keywords = [w.lower() for w in re.findall(r'\b[a-zA-Z]{4,}\b', sent)][:6]
|
| 195 |
+
behaviors.append(Behavior(
|
| 196 |
+
id=f"B{bid:03d}", description=f"Security: {sent[:80]}",
|
| 197 |
+
category="security", priority="critical", source="requirements",
|
| 198 |
+
keywords=keywords + ["security", "auth"]
|
| 199 |
+
))
|
| 200 |
bid += 1
|
| 201 |
|
| 202 |
+
# From API spec
|
| 203 |
if api_spec:
|
| 204 |
for path, methods in api_spec.get("paths", {}).items():
|
| 205 |
for method, details in methods.items():
|
| 206 |
if method not in ("get", "post", "put", "patch", "delete"):
|
| 207 |
continue
|
| 208 |
+
path_words = [w for w in re.split(r'[/{}]', path) if w and len(w) > 2]
|
| 209 |
+
|
| 210 |
+
behaviors.append(Behavior(
|
| 211 |
+
id=f"B{bid:03d}",
|
| 212 |
+
description=f"{method.upper()} {path} returns success (200/201)",
|
| 213 |
+
category="happy_path", priority="critical", source=f"api:{method}:{path}",
|
| 214 |
+
keywords=[method, "200", "success"] + path_words
|
| 215 |
+
))
|
| 216 |
bid += 1
|
| 217 |
+
behaviors.append(Behavior(
|
| 218 |
+
id=f"B{bid:03d}",
|
| 219 |
+
description=f"{method.upper()} {path} returns 401 without authentication",
|
| 220 |
+
category="security", priority="high", source=f"api:{method}:{path}",
|
| 221 |
+
keywords=[method, "401", "auth", "unauthorized", "token"] + path_words
|
| 222 |
+
))
|
| 223 |
bid += 1
|
| 224 |
+
behaviors.append(Behavior(
|
| 225 |
+
id=f"B{bid:03d}",
|
| 226 |
+
description=f"{method.upper()} {path} returns 400/422 with invalid body",
|
| 227 |
+
category="error_handling", priority="high", source=f"api:{method}:{path}",
|
| 228 |
+
keywords=[method, "400", "422", "invalid", "validation"] + path_words
|
| 229 |
+
))
|
| 230 |
bid += 1
|
| 231 |
+
if method in ("post", "put", "patch"):
|
| 232 |
+
behaviors.append(Behavior(
|
| 233 |
+
id=f"B{bid:03d}",
|
| 234 |
+
description=f"{method.upper()} {path} rejects SQL injection in string fields",
|
| 235 |
+
category="security", priority="critical", source=f"api:{method}:{path}",
|
| 236 |
+
keywords=[method, "sql", "injection", "xss", "sanitize"] + path_words
|
| 237 |
+
))
|
| 238 |
bid += 1
|
| 239 |
+
behaviors.append(Behavior(
|
| 240 |
+
id=f"B{bid:03d}",
|
| 241 |
+
description=f"{method.upper()} {path} respects rate limits (429)",
|
| 242 |
+
category="security", priority="medium", source=f"api:{method}:{path}",
|
| 243 |
+
keywords=[method, "rate", "limit", "429", "throttle"] + path_words
|
| 244 |
+
))
|
| 245 |
+
bid += 1
|
| 246 |
|
| 247 |
return behaviors
|
| 248 |
|
| 249 |
|
| 250 |
+
def _get_exception_name(node) -> str:
|
| 251 |
+
if node.exc is None:
|
| 252 |
+
return "Exception"
|
| 253 |
+
if isinstance(node.exc, ast.Call):
|
| 254 |
+
if isinstance(node.exc.func, ast.Name):
|
| 255 |
+
return node.exc.func.id
|
| 256 |
+
elif isinstance(node.exc.func, ast.Attribute):
|
| 257 |
+
return node.exc.func.attr
|
| 258 |
+
elif isinstance(node.exc, ast.Name):
|
| 259 |
+
return node.exc.id
|
| 260 |
+
return "Exception"
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def _find_external_calls(func_node) -> List[str]:
|
| 264 |
+
calls = []
|
| 265 |
+
for node in ast.walk(func_node):
|
| 266 |
+
if isinstance(node, ast.Call):
|
| 267 |
+
if isinstance(node.func, ast.Attribute):
|
| 268 |
+
if isinstance(node.func.value, ast.Name):
|
| 269 |
+
if node.func.value.id not in ('self', 'cls', 'super'):
|
| 270 |
+
calls.append(f"{node.func.value.id}.{node.func.attr}")
|
| 271 |
+
return list(set(calls))
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 275 |
+
# TEST SYNTAX VALIDATION (FIX: Actually compiles generated tests)
|
| 276 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 277 |
+
|
| 278 |
+
def validate_test_syntax(test_code: str, language: str = "python") -> Dict[str, Any]:
|
| 279 |
+
"""Actually parse/compile generated test code to verify syntax."""
|
| 280 |
+
if language == "python":
|
| 281 |
+
return _validate_python_syntax(test_code)
|
| 282 |
+
elif language in ("javascript", "typescript"):
|
| 283 |
+
return _validate_js_syntax(test_code)
|
| 284 |
+
return {"valid": True, "errors": [], "warnings": []}
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
def _validate_python_syntax(code: str) -> Dict[str, Any]:
|
| 288 |
+
errors, warnings = [], []
|
| 289 |
+
clean_code = re.sub(r'^```\w*\n|```$', '', code, flags=re.MULTILINE).strip()
|
| 290 |
+
|
| 291 |
+
try:
|
| 292 |
+
tree = ast.parse(clean_code)
|
| 293 |
+
test_funcs = [n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef) and n.name.startswith('test_')]
|
| 294 |
+
test_classes = [n for n in ast.walk(tree) if isinstance(n, ast.ClassDef) and n.name.startswith('Test')]
|
| 295 |
+
|
| 296 |
+
if not test_funcs and not test_classes:
|
| 297 |
+
warnings.append("No test functions (test_*) or test classes (Test*) found")
|
| 298 |
+
|
| 299 |
+
has_assert = any(isinstance(n, ast.Assert) for n in ast.walk(tree))
|
| 300 |
+
has_assert_call = 'assert' in clean_code.lower() or 'raises' in clean_code
|
| 301 |
+
if not has_assert and not has_assert_call:
|
| 302 |
+
warnings.append("No assertions found in test code")
|
| 303 |
+
|
| 304 |
+
return {
|
| 305 |
+
"valid": True, "errors": errors, "warnings": warnings,
|
| 306 |
+
"test_count": len(test_funcs), "class_count": len(test_classes),
|
| 307 |
+
"has_assertions": has_assert or has_assert_call,
|
| 308 |
+
"lines": len(clean_code.split('\n')),
|
| 309 |
+
}
|
| 310 |
+
except SyntaxError as e:
|
| 311 |
+
return {
|
| 312 |
+
"valid": False,
|
| 313 |
+
"errors": [f"SyntaxError at line {e.lineno}: {e.msg}"],
|
| 314 |
+
"warnings": [], "test_count": 0, "class_count": 0,
|
| 315 |
+
"has_assertions": False, "lines": 0,
|
| 316 |
+
}
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
def _validate_js_syntax(code: str) -> Dict[str, Any]:
|
| 320 |
+
errors, warnings = [], []
|
| 321 |
+
clean_code = re.sub(r'^```\w*\n|```$', '', code, flags=re.MULTILINE).strip()
|
| 322 |
+
|
| 323 |
+
opens = clean_code.count('{')
|
| 324 |
+
closes = clean_code.count('}')
|
| 325 |
+
if opens != closes:
|
| 326 |
+
errors.append(f"Unbalanced braces: {opens} opening, {closes} closing")
|
| 327 |
+
|
| 328 |
+
test_blocks = len(re.findall(r'\b(it|test|describe)\s*\(', clean_code))
|
| 329 |
+
if test_blocks == 0:
|
| 330 |
+
warnings.append("No test blocks (it/test/describe) found")
|
| 331 |
+
|
| 332 |
+
has_expect = 'expect(' in clean_code or 'assert' in clean_code
|
| 333 |
+
if not has_expect:
|
| 334 |
+
warnings.append("No assertions (expect/assert) found")
|
| 335 |
+
|
| 336 |
+
return {
|
| 337 |
+
"valid": len(errors) == 0, "errors": errors, "warnings": warnings,
|
| 338 |
+
"test_count": test_blocks, "has_assertions": has_expect,
|
| 339 |
+
"lines": len(clean_code.split('\n')),
|
| 340 |
+
}
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 344 |
+
# SEMANTIC COVERAGE MAPPING (FIX: AST-based, not keyword matching)
|
| 345 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 346 |
+
|
| 347 |
+
@dataclass
|
| 348 |
+
class TestSignature:
|
| 349 |
+
name: str
|
| 350 |
+
docstring: str = ""
|
| 351 |
+
called_functions: List[str] = field(default_factory=list)
|
| 352 |
+
keywords: Set[str] = field(default_factory=set)
|
| 353 |
+
tests_exception: bool = False
|
| 354 |
+
tests_none: bool = False
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
def map_behavior_coverage_semantic(behaviors: List[Behavior], test_code: str, language: str = "python") -> Dict[str, Any]:
|
| 358 |
+
"""FIX: AST-based semantic coverage mapping."""
|
| 359 |
+
if language == "python":
|
| 360 |
+
test_signatures = _extract_python_test_signatures(test_code)
|
| 361 |
+
else:
|
| 362 |
+
test_signatures = _extract_js_test_signatures(test_code)
|
| 363 |
+
|
| 364 |
+
covered = 0
|
| 365 |
+
uncovered_list = []
|
| 366 |
+
|
| 367 |
+
for b in behaviors:
|
| 368 |
+
is_covered = _behavior_matches_tests(b, test_signatures)
|
| 369 |
+
b.tested = is_covered
|
| 370 |
+
if is_covered:
|
| 371 |
+
covered += 1
|
| 372 |
+
else:
|
| 373 |
+
uncovered_list.append({
|
| 374 |
+
"id": b.id, "description": b.description,
|
| 375 |
+
"priority": b.priority, "category": b.category,
|
| 376 |
+
"suggestion": _suggest_test_for_behavior(b),
|
| 377 |
+
})
|
| 378 |
+
|
| 379 |
+
total = max(len(behaviors), 1)
|
| 380 |
+
return {
|
| 381 |
+
"total_behaviors": len(behaviors),
|
| 382 |
+
"covered": covered,
|
| 383 |
+
"uncovered": len(behaviors) - covered,
|
| 384 |
+
"coverage_pct": round((covered / total) * 100, 1),
|
| 385 |
+
"uncovered_behaviors": uncovered_list[:20],
|
| 386 |
+
"by_category": {
|
| 387 |
+
cat: {
|
| 388 |
+
"total": len([b for b in behaviors if b.category == cat]),
|
| 389 |
+
"tested": len([b for b in behaviors if b.category == cat and b.tested]),
|
| 390 |
+
"coverage_pct": round(
|
| 391 |
+
len([b for b in behaviors if b.category == cat and b.tested]) /
|
| 392 |
+
max(len([b for b in behaviors if b.category == cat]), 1) * 100, 1
|
| 393 |
+
)
|
| 394 |
+
}
|
| 395 |
+
for cat in set(b.category for b in behaviors)
|
| 396 |
+
},
|
| 397 |
+
"test_signatures_found": len(test_signatures),
|
| 398 |
+
}
|
| 399 |
+
|
| 400 |
+
|
| 401 |
+
def _extract_python_test_signatures(code: str) -> List[TestSignature]:
|
| 402 |
+
signatures = []
|
| 403 |
+
clean_code = re.sub(r'^```\w*\n|```$', '', code, flags=re.MULTILINE).strip()
|
| 404 |
+
|
| 405 |
+
try:
|
| 406 |
+
tree = ast.parse(clean_code)
|
| 407 |
+
except SyntaxError:
|
| 408 |
+
return _extract_signatures_regex(code)
|
| 409 |
+
|
| 410 |
+
for node in ast.walk(tree):
|
| 411 |
+
if isinstance(node, ast.FunctionDef) and node.name.startswith('test_'):
|
| 412 |
+
sig = TestSignature(name=node.name)
|
| 413 |
+
|
| 414 |
+
# Docstring
|
| 415 |
+
if (node.body and isinstance(node.body[0], ast.Expr) and
|
| 416 |
+
isinstance(node.body[0].value, ast.Constant) and isinstance(node.body[0].value.value, str)):
|
| 417 |
+
sig.docstring = node.body[0].value.value
|
| 418 |
+
|
| 419 |
+
# Called functions
|
| 420 |
+
for child in ast.walk(node):
|
| 421 |
+
if isinstance(child, ast.Call):
|
| 422 |
+
if isinstance(child.func, ast.Name):
|
| 423 |
+
sig.called_functions.append(child.func.id)
|
| 424 |
+
elif isinstance(child.func, ast.Attribute):
|
| 425 |
+
sig.called_functions.append(child.func.attr)
|
| 426 |
+
|
| 427 |
+
# Exception testing
|
| 428 |
+
sig.tests_exception = any(
|
| 429 |
+
isinstance(child, ast.Call) and isinstance(child.func, ast.Attribute) and child.func.attr == 'raises'
|
| 430 |
+
for child in ast.walk(node)
|
| 431 |
+
) or 'raises' in node.name or 'error' in node.name or 'exception' in node.name
|
| 432 |
+
|
| 433 |
+
sig.tests_none = 'none' in node.name.lower() or 'null' in node.name.lower()
|
| 434 |
+
|
| 435 |
+
# Keywords from name + docstring
|
| 436 |
+
name_words = set(node.name.replace('test_', '').split('_'))
|
| 437 |
+
doc_words = set(re.findall(r'\b[a-z]{3,}\b', sig.docstring.lower())) if sig.docstring else set()
|
| 438 |
+
sig.keywords = name_words | doc_words | set(sig.called_functions)
|
| 439 |
+
|
| 440 |
+
signatures.append(sig)
|
| 441 |
+
|
| 442 |
+
return signatures
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
def _extract_js_test_signatures(code: str) -> List[TestSignature]:
|
| 446 |
+
signatures = []
|
| 447 |
+
for match in re.finditer(r"(?:it|test)\s*\(\s*['\"](.+?)['\"]", code):
|
| 448 |
+
desc = match.group(1)
|
| 449 |
+
sig = TestSignature(name=desc, docstring=desc)
|
| 450 |
+
sig.keywords = set(re.findall(r'\b[a-z]{3,}\b', desc.lower()))
|
| 451 |
+
sig.tests_exception = any(kw in desc.lower() for kw in ['error', 'throw', 'reject', 'fail'])
|
| 452 |
+
sig.tests_none = any(kw in desc.lower() for kw in ['null', 'undefined', 'empty'])
|
| 453 |
+
signatures.append(sig)
|
| 454 |
+
return signatures
|
| 455 |
+
|
| 456 |
+
|
| 457 |
+
def _extract_signatures_regex(code: str) -> List[TestSignature]:
|
| 458 |
+
signatures = []
|
| 459 |
+
for match in re.finditer(r'def (test_\w+)', code):
|
| 460 |
+
name = match.group(1)
|
| 461 |
+
sig = TestSignature(name=name)
|
| 462 |
+
sig.keywords = set(name.replace('test_', '').split('_'))
|
| 463 |
+
sig.tests_exception = 'raises' in name or 'error' in name
|
| 464 |
+
sig.tests_none = 'none' in name or 'null' in name
|
| 465 |
+
signatures.append(sig)
|
| 466 |
+
return signatures
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
def _behavior_matches_tests(behavior: Behavior, signatures: List[TestSignature]) -> bool:
|
| 470 |
+
"""Semantic matching using multi-signal scoring."""
|
| 471 |
+
b_keywords = set(kw.lower() for kw in behavior.keywords if len(kw) > 2)
|
| 472 |
+
b_desc_words = set(re.findall(r'\b[a-z]{4,}\b', behavior.description.lower()))
|
| 473 |
+
all_b_words = b_keywords | b_desc_words
|
| 474 |
+
|
| 475 |
+
for sig in signatures:
|
| 476 |
+
score = 0
|
| 477 |
+
overlap = all_b_words & sig.keywords
|
| 478 |
+
score += len(overlap) * 2
|
| 479 |
+
|
| 480 |
+
for kw in b_keywords:
|
| 481 |
+
if kw in sig.name.lower():
|
| 482 |
+
score += 3
|
| 483 |
+
|
| 484 |
+
if sig.docstring:
|
| 485 |
+
doc_overlap = all_b_words & set(re.findall(r'\b[a-z]{3,}\b', sig.docstring.lower()))
|
| 486 |
+
score += len(doc_overlap)
|
| 487 |
+
|
| 488 |
+
if behavior.category == "error_handling" and sig.tests_exception:
|
| 489 |
+
score += 3
|
| 490 |
+
if behavior.category == "edge_case" and sig.tests_none:
|
| 491 |
+
score += 2
|
| 492 |
+
if behavior.category == "edge_case" and any(kw in sig.name for kw in ['empty', 'zero', 'boundary', 'edge']):
|
| 493 |
+
score += 3
|
| 494 |
+
if behavior.category == "security" and any(kw in sig.name for kw in ['inject', 'auth', 'xss', 'sql', 'security']):
|
| 495 |
+
score += 3
|
| 496 |
+
|
| 497 |
+
source_func = behavior.source.split(':')[-1] if ':' in behavior.source else ""
|
| 498 |
+
if source_func and source_func in sig.called_functions:
|
| 499 |
+
score += 4
|
| 500 |
+
|
| 501 |
+
if score >= 4:
|
| 502 |
+
return True
|
| 503 |
+
|
| 504 |
+
return False
|
| 505 |
+
|
| 506 |
+
|
| 507 |
+
def _suggest_test_for_behavior(behavior: Behavior) -> str:
|
| 508 |
+
func = behavior.source.split(':')[-1] if ':' in behavior.source else "target"
|
| 509 |
+
if behavior.category == "edge_case":
|
| 510 |
+
return f"def test_{func}_edge_{behavior.id.lower()}(): # {behavior.description[:50]}"
|
| 511 |
+
elif behavior.category == "error_handling":
|
| 512 |
+
return f"def test_{func}_raises_on_invalid(): # pytest.raises(...)"
|
| 513 |
+
elif behavior.category == "security":
|
| 514 |
+
return f"def test_{func}_rejects_malicious_input(): # injection payloads"
|
| 515 |
+
return f"def test_{func}_{behavior.id.lower()}(): # {behavior.description[:40]}"
|
| 516 |
+
|
| 517 |
+
|
| 518 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 519 |
+
# MULTI-AGENT ITERATIVE REFINEMENT ENGINE (v2)
|
| 520 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 521 |
|
| 522 |
async def run_multi_agent_pipeline(
|
|
|
|
| 526 |
framework: str = "pytest",
|
| 527 |
language: str = "python",
|
| 528 |
test_types: List[str] = None,
|
| 529 |
+
max_iterations: int = 3,
|
| 530 |
) -> Dict[str, Any]:
|
| 531 |
"""
|
| 532 |
+
Full multi-agent iterative refinement pipeline (v2).
|
| 533 |
+
Now with real mutation execution, syntax validation, and semantic coverage.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 534 |
"""
|
| 535 |
start_time = time.time()
|
| 536 |
run_id = f"MAS-{uuid.uuid4().hex[:8]}"
|
| 537 |
test_types = test_types or ["unit", "integration", "edge_case", "security"]
|
| 538 |
+
max_iterations = min(max_iterations, 5)
|
| 539 |
|
| 540 |
# βββ AGENT 1: ANALYZER βββ
|
| 541 |
analysis = {
|
|
|
|
| 544 |
"gaps": detect_coverage_gaps(source_code) if source_code else None,
|
| 545 |
}
|
| 546 |
|
| 547 |
+
suggested_tests = 15
|
| 548 |
+
if analysis["complexity"]:
|
| 549 |
+
suggested_tests = max(10, min(30, analysis["complexity"].get("suggested_total_tests", 15)))
|
| 550 |
+
|
| 551 |
+
# βββ AGENT 2: GENERATOR βββ
|
| 552 |
input_context = _build_rich_context(source_code, requirements, api_spec, analysis)
|
| 553 |
+
system_prompt = _build_system_prompt(framework, language, suggested_tests)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 554 |
|
| 555 |
gen_prompt = f"""Generate {framework} tests in {language}.
|
| 556 |
Test types: {', '.join(test_types)}
|
| 557 |
+
Target: {suggested_tests}+ test functions.
|
| 558 |
|
| 559 |
CONTEXT:
|
| 560 |
{input_context}
|
| 561 |
|
| 562 |
BEHAVIORS TO TEST ({len(analysis['behaviors'])} identified):
|
| 563 |
+
{chr(10).join(f'- [{b.priority.upper()}][{b.category}] {b.description}' for b in analysis['behaviors'][:25])}
|
| 564 |
+
|
| 565 |
+
{_get_few_shot_example(framework, language)}
|
| 566 |
|
| 567 |
Generate the complete test file now:"""
|
| 568 |
|
| 569 |
raw_tests = await generate_with_llm(gen_prompt, system_prompt, temperature=0.3)
|
| 570 |
|
| 571 |
+
# βββ AGENT 3: VALIDATOR βββ
|
| 572 |
+
syntax_result = validate_test_syntax(raw_tests, language)
|
| 573 |
quality_score = score_test_quality(raw_tests)
|
|
|
|
| 574 |
|
| 575 |
+
# Fix syntax if broken
|
| 576 |
+
if not syntax_result["valid"]:
|
| 577 |
+
fix_prompt = f"""Fix the syntax errors in these tests.
|
| 578 |
+
ERRORS: {chr(10).join(syntax_result['errors'])}
|
| 579 |
+
|
| 580 |
+
```
|
| 581 |
+
{raw_tests[:4000]}
|
| 582 |
+
```
|
| 583 |
+
|
| 584 |
+
Output the FIXED complete test code:"""
|
| 585 |
+
raw_tests = await generate_with_llm(fix_prompt, system_prompt, temperature=0.1)
|
| 586 |
+
syntax_result = validate_test_syntax(raw_tests, language)
|
| 587 |
+
quality_score = score_test_quality(raw_tests)
|
| 588 |
+
|
| 589 |
+
# βββ AGENT 4: REFINER βββ
|
| 590 |
refined_tests = raw_tests
|
| 591 |
refinement_history = []
|
| 592 |
+
mutation_results = None
|
| 593 |
|
| 594 |
for iteration in range(max_iterations):
|
| 595 |
+
if quality_score["overall"] >= 85 and syntax_result.get("valid", True):
|
| 596 |
+
break
|
| 597 |
+
|
| 598 |
+
# Real mutation execution
|
| 599 |
+
if source_code and language == "python":
|
| 600 |
+
mutation_results = execute_mutations(source_code, refined_tests)
|
| 601 |
+
else:
|
| 602 |
+
mutation_results = suggest_mutations(source_code) if source_code else {"mutations": [], "total_mutations": 0}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 603 |
|
| 604 |
+
weak_areas = _identify_weaknesses(quality_score, mutation_results, syntax_result)
|
| 605 |
if not weak_areas:
|
| 606 |
break
|
| 607 |
|
| 608 |
+
mutation_feedback = ""
|
| 609 |
+
if mutation_results and mutation_results.get("surviving_mutants"):
|
| 610 |
+
survivors = mutation_results["surviving_mutants"][:5]
|
| 611 |
+
mutation_feedback = f"""
|
| 612 |
+
SURVIVING MUTANTS (tests FAILED to catch these):
|
| 613 |
+
{chr(10).join(f' β’ Line {m["line"]}: {m["description"]}' for m in survivors)}
|
| 614 |
+
Write tests that KILL these mutants."""
|
| 615 |
|
| 616 |
+
refine_prompt = f"""IMPROVE tests. Quality: {quality_score['overall']}/100 (Grade {quality_score['grade']}).
|
| 617 |
+
|
| 618 |
+
WEAKNESSES:
|
| 619 |
{chr(10).join(f'{i+1}. {w}' for i, w in enumerate(weak_areas))}
|
| 620 |
+
{mutation_feedback}
|
| 621 |
|
| 622 |
CURRENT TESTS:
|
| 623 |
```
|
| 624 |
+
{refined_tests[:4000]}
|
| 625 |
```
|
| 626 |
|
| 627 |
+
Keep all good tests, ADD new ones for gaps. Output COMPLETE improved test file:"""
|
| 628 |
|
| 629 |
refined_tests = await generate_with_llm(refine_prompt, system_prompt, temperature=0.2)
|
| 630 |
+
syntax_result = validate_test_syntax(refined_tests, language)
|
| 631 |
+
new_quality = score_test_quality(refined_tests)
|
| 632 |
+
|
| 633 |
refinement_history.append({
|
| 634 |
"iteration": iteration + 1,
|
| 635 |
"quality_before": quality_score["overall"],
|
| 636 |
+
"quality_after": new_quality["overall"],
|
| 637 |
"weaknesses_addressed": weak_areas,
|
| 638 |
+
"mutation_survivors": mutation_results.get("surviving_count", 0) if mutation_results else 0,
|
| 639 |
+
"syntax_valid": syntax_result.get("valid", True),
|
| 640 |
})
|
| 641 |
+
quality_score = new_quality
|
| 642 |
|
| 643 |
+
# βββ AGENT 5: COVERAGE MAPPER βββ
|
| 644 |
+
behavior_coverage = map_behavior_coverage_semantic(analysis["behaviors"], refined_tests, language)
|
| 645 |
|
| 646 |
+
final_syntax = validate_test_syntax(refined_tests, language)
|
| 647 |
processing_time = (time.time() - start_time) * 1000
|
| 648 |
|
| 649 |
return {
|
| 650 |
"run_id": run_id,
|
| 651 |
+
"pipeline": "multi-agent-iterative-v2",
|
| 652 |
"status": "completed",
|
| 653 |
"timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ"),
|
|
|
|
|
|
|
| 654 |
"test_code": refined_tests,
|
| 655 |
"test_files": _parse_to_files(refined_tests, framework, language),
|
|
|
|
|
|
|
| 656 |
"quality": quality_score,
|
| 657 |
"iterations_performed": len(refinement_history),
|
| 658 |
"refinement_history": refinement_history,
|
| 659 |
+
"syntax_validation": final_syntax,
|
|
|
|
| 660 |
"behavior_coverage": behavior_coverage,
|
| 661 |
+
"mutation_testing": {
|
| 662 |
+
"total_mutants": mutation_results.get("total_mutations", 0) if mutation_results else 0,
|
| 663 |
+
"killed": mutation_results.get("killed_count", 0) if mutation_results else 0,
|
| 664 |
+
"survived": mutation_results.get("surviving_count", 0) if mutation_results else 0,
|
| 665 |
+
"mutation_score": mutation_results.get("mutation_score", 0) if mutation_results else 0,
|
| 666 |
+
"surviving_mutants": mutation_results.get("surviving_mutants", [])[:10] if mutation_results else [],
|
| 667 |
+
},
|
| 668 |
"analysis": {
|
| 669 |
"total_behaviors": len(analysis["behaviors"]),
|
| 670 |
"behaviors_tested": behavior_coverage["covered"],
|
|
|
|
| 672 |
"coverage_pct": behavior_coverage["coverage_pct"],
|
| 673 |
"complexity": analysis.get("complexity"),
|
| 674 |
"gaps": analysis.get("gaps"),
|
|
|
|
| 675 |
},
|
|
|
|
| 676 |
"processing_time_ms": round(processing_time, 1),
|
| 677 |
}
|
| 678 |
|
|
|
|
| 681 |
# HELPERS
|
| 682 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 683 |
|
| 684 |
+
def _build_system_prompt(framework: str, language: str, target_tests: int) -> str:
|
| 685 |
+
return f"""You are TestGenius, an expert QA automation engineer.
|
| 686 |
+
Generate COMPREHENSIVE, RUNNABLE {framework} test code in {language}.
|
| 687 |
+
|
| 688 |
+
RULES:
|
| 689 |
+
1. Include ALL necessary imports.
|
| 690 |
+
2. Every test MUST have 2+ assertions.
|
| 691 |
+
3. Descriptive names: test_<what>_<scenario>_<expected>.
|
| 692 |
+
4. Docstring per test explaining what's verified.
|
| 693 |
+
5. Cover: happy path, edge cases, boundary values, errors.
|
| 694 |
+
6. For errors: verify exception type AND message.
|
| 695 |
+
7. Mock external dependencies properly.
|
| 696 |
+
8. Generate {target_tests}+ test functions.
|
| 697 |
+
9. Group related tests logically.
|
| 698 |
+
10. Output ONLY valid {language} code in a single code block."""
|
| 699 |
+
|
| 700 |
+
|
| 701 |
def _build_rich_context(code: str, reqs: str, api: dict, analysis: dict) -> str:
|
|
|
|
| 702 |
parts = []
|
| 703 |
if code:
|
| 704 |
+
parts.append(f"SOURCE CODE:\n```\n{code[:4000]}\n```")
|
| 705 |
if analysis.get("complexity"):
|
| 706 |
c = analysis["complexity"]
|
| 707 |
+
high_funcs = [f for f in c.get("functions", []) if f.get("priority") == "HIGH"]
|
| 708 |
+
if high_funcs:
|
| 709 |
+
parts.append("β οΈ HIGH-COMPLEXITY FUNCTIONS:\n" +
|
| 710 |
+
"\n".join(f" β’ {f['name']}() β complexity {f['complexity']}, needs {f['suggested_tests']}+ tests" for f in high_funcs))
|
| 711 |
+
if analysis.get("gaps"):
|
| 712 |
+
g = analysis["gaps"]
|
| 713 |
+
if g.get("high_priority", 0) > 0:
|
| 714 |
+
parts.append(f"β οΈ COVERAGE GAPS ({g['high_priority']} high-priority):\n" +
|
| 715 |
+
"\n".join(f" β’ {gap['desc']}" for gap in g.get("gaps", [])[:5] if gap["priority"] == "HIGH"))
|
| 716 |
if reqs:
|
| 717 |
+
parts.append(f"REQUIREMENTS:\n{reqs[:2500]}")
|
| 718 |
if api:
|
| 719 |
endpoints = []
|
| 720 |
for path, methods in api.get("paths", {}).items():
|
| 721 |
for method in methods:
|
| 722 |
+
if method in ("get", "post", "put", "patch", "delete"):
|
| 723 |
endpoints.append(f" {method.upper()} {path}")
|
| 724 |
+
parts.append(f"API ENDPOINTS:\n{chr(10).join(endpoints[:20])}")
|
| 725 |
return "\n\n".join(parts)
|
| 726 |
|
| 727 |
|
| 728 |
+
def _get_few_shot_example(framework: str, language: str) -> str:
|
| 729 |
+
if framework == "pytest" and language == "python":
|
| 730 |
+
return """
|
| 731 |
+
EXAMPLE OF IDEAL QUALITY:
|
| 732 |
+
```python
|
| 733 |
+
import pytest
|
| 734 |
+
|
| 735 |
+
def test_calculate_discount_premium_user_gets_20_percent():
|
| 736 |
+
\"\"\"Premium users receive exactly 20% discount.\"\"\"
|
| 737 |
+
result = calculate_discount(100.0, "premium")
|
| 738 |
+
assert result == 20.0
|
| 739 |
+
assert isinstance(result, float)
|
| 740 |
+
|
| 741 |
+
def test_calculate_discount_negative_price_raises_value_error():
|
| 742 |
+
\"\"\"Negative prices must raise ValueError.\"\"\"
|
| 743 |
+
with pytest.raises(ValueError, match="Price must be positive"):
|
| 744 |
+
calculate_discount(-10, "standard")
|
| 745 |
+
|
| 746 |
+
@pytest.mark.parametrize("user_type,expected", [("premium", 20.0), ("member", 10.0)])
|
| 747 |
+
def test_calculate_discount_user_types(user_type, expected):
|
| 748 |
+
\"\"\"Each user type gets correct discount.\"\"\"
|
| 749 |
+
assert calculate_discount(100.0, user_type) == expected
|
| 750 |
+
```
|
| 751 |
+
Follow this pattern."""
|
| 752 |
+
elif framework in ("jest", "vitest"):
|
| 753 |
+
return """
|
| 754 |
+
EXAMPLE:
|
| 755 |
+
```javascript
|
| 756 |
+
describe('calculateDiscount', () => {
|
| 757 |
+
test('premium user gets 20% discount', () => {
|
| 758 |
+
const result = calculateDiscount(100, 'premium');
|
| 759 |
+
expect(result).toBe(20);
|
| 760 |
+
expect(typeof result).toBe('number');
|
| 761 |
+
});
|
| 762 |
+
test('throws for negative price', () => {
|
| 763 |
+
expect(() => calculateDiscount(-10, 'standard')).toThrow('Price must be positive');
|
| 764 |
+
});
|
| 765 |
+
});
|
| 766 |
+
```"""
|
| 767 |
+
return ""
|
| 768 |
+
|
| 769 |
+
|
| 770 |
+
def _identify_weaknesses(quality: Dict, mutations: Dict, syntax: Dict) -> List[str]:
|
| 771 |
+
weak_areas = []
|
| 772 |
+
if not syntax.get("valid", True):
|
| 773 |
+
weak_areas.append(f"FIX SYNTAX: {'; '.join(syntax.get('errors', [])[:3])}")
|
| 774 |
+
|
| 775 |
+
scores = quality.get("scores", {})
|
| 776 |
+
if scores.get("edge_cases", 0) < 7:
|
| 777 |
+
weak_areas.append("ADD EDGE CASES: None, empty, boundary, Unicode, negative")
|
| 778 |
+
if scores.get("error_handling", 0) < 7:
|
| 779 |
+
weak_areas.append("ADD ERROR TESTS: invalid types, missing fields, pytest.raises()")
|
| 780 |
+
if scores.get("assertions", 0) < 7:
|
| 781 |
+
weak_areas.append("STRENGTHEN ASSERTIONS: 2+ per test, check type AND value")
|
| 782 |
+
if scores.get("docs", 0) < 5:
|
| 783 |
+
weak_areas.append("ADD DOCSTRINGS per test")
|
| 784 |
+
if scores.get("isolation", 0) < 6:
|
| 785 |
+
weak_areas.append("ADD FIXTURES: @pytest.fixture or mock externals")
|
| 786 |
+
|
| 787 |
+
if mutations and mutations.get("surviving_mutants"):
|
| 788 |
+
weak_areas.append(f"KILL {mutations.get('surviving_count', 0)} surviving mutations")
|
| 789 |
+
|
| 790 |
+
return weak_areas[:5]
|
| 791 |
|
| 792 |
|
| 793 |
def _parse_to_files(raw: str, framework: str, language: str) -> List[Dict]:
|
|
|
|
| 794 |
files = []
|
| 795 |
code_blocks = re.findall(r'```(?:\w+)?\s*(.*?)```', raw, re.DOTALL)
|
| 796 |
+
|
| 797 |
if code_blocks:
|
| 798 |
for i, block in enumerate(code_blocks):
|
| 799 |
+
block = block.strip()
|
| 800 |
+
if not block or len(block) < 20:
|
| 801 |
+
continue
|
| 802 |
+
ext = ".py" if language == "python" else ".js" if language in ("javascript", "typescript") else ".go"
|
| 803 |
files.append({
|
| 804 |
+
"filename": f"test_generated_{i+1}{ext}" if i > 0 else f"test_generated{ext}",
|
| 805 |
+
"framework": framework, "language": language, "code": block,
|
|
|
|
|
|
|
| 806 |
"num_tests": block.count("def test_") + block.count("it(") + block.count("test("),
|
| 807 |
})
|
| 808 |
else:
|
| 809 |
ext = ".py" if language == "python" else ".js"
|
| 810 |
files.append({
|
| 811 |
"filename": f"test_generated{ext}",
|
| 812 |
+
"framework": framework, "language": language, "code": raw,
|
|
|
|
|
|
|
| 813 |
"num_tests": raw.count("def test_") + raw.count("it(") + raw.count("test("),
|
| 814 |
})
|
| 815 |
|