diff-to-test 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- diff2test/__init__.py +3 -0
- diff2test/__main__.py +6 -0
- diff2test/cli.py +393 -0
- diff2test/config.py +213 -0
- diff2test/context_builder.py +318 -0
- diff2test/git_handler.py +255 -0
- diff2test/github_api.py +408 -0
- diff2test/llm_client.py +301 -0
- diff2test/models.py +106 -0
- diff2test/pipeline.py +79 -0
- diff2test/profiles/__init__.py +126 -0
- diff2test/profiles/dart-flutter.yaml +17 -0
- diff2test/profiles/generic.yaml +17 -0
- diff2test/profiles/python-fastapi.yaml +19 -0
- diff2test/prompts/__init__.py +11 -0
- diff2test/prompts/fix.md +22 -0
- diff2test/prompts/generate.md +23 -0
- diff2test/prompts/system.md +8 -0
- diff2test/runner.py +382 -0
- diff2test/summary.py +18 -0
- diff2test/symbols.py +99 -0
- diff_to_test-0.0.1.dist-info/METADATA +140 -0
- diff_to_test-0.0.1.dist-info/RECORD +26 -0
- diff_to_test-0.0.1.dist-info/WHEEL +4 -0
- diff_to_test-0.0.1.dist-info/entry_points.txt +2 -0
- diff_to_test-0.0.1.dist-info/licenses/LICENSE +21 -0
diff2test/prompts/fix.md
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
The previous test attempt (#{attempt_number}) for `{target_test_path}` failed. Fix the test file without deleting or weakening assertions.
|
|
2
|
+
|
|
3
|
+
- **Source file:** `{source_path}`
|
|
4
|
+
- **Exit code:** `{exit_code}`
|
|
5
|
+
- **Guard violations:** {guard_violations}
|
|
6
|
+
|
|
7
|
+
## Previous Test Code
|
|
8
|
+
```
|
|
9
|
+
{previous_code}
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
## Test Output (tail)
|
|
13
|
+
```
|
|
14
|
+
{error_output}
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Source Code Context
|
|
18
|
+
```
|
|
19
|
+
{source_code}
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
Return only a single fenced code block with the corrected, complete contents of `{target_test_path}`.
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
Generate unit tests for the changed source file below.
|
|
2
|
+
|
|
3
|
+
- **Source file:** `{source_path}` (`{language}`)
|
|
4
|
+
- **Target test file:** `{target_test_path}`
|
|
5
|
+
- **Changed symbols:** {changed_symbols}
|
|
6
|
+
|
|
7
|
+
## Profile & Project Instructions
|
|
8
|
+
{profile_instructions}
|
|
9
|
+
|
|
10
|
+
## Added / Changed Diff Lines
|
|
11
|
+
```diff
|
|
12
|
+
{diff_lines}
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Source Code Context
|
|
16
|
+
```
|
|
17
|
+
{source_code}
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## Example Tests (Style Reference)
|
|
21
|
+
{example_tests}
|
|
22
|
+
|
|
23
|
+
Return only a single fenced code block with the complete contents of `{target_test_path}`.
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
You are an expert autonomous software test engineer.
|
|
2
|
+
|
|
3
|
+
Follow these strict rules:
|
|
4
|
+
1. Return **only a single fenced code block** containing the complete, runnable test file (no prose before or after).
|
|
5
|
+
2. Mirror the exact test framework, mocking library, imports, and naming conventions from the provided example tests.
|
|
6
|
+
3. Cover both happy paths and edge cases (`null`/`None`, empty collections, boundary values, and error paths).
|
|
7
|
+
4. Never invent or call functions, classes, methods, or imports that do not exist in the source code.
|
|
8
|
+
5. Never delete, comment out, or weaken assertions (and never emit `assert True`, `skip`, or empty tests) to make a failing test pass.
|
diff2test/runner.py
ADDED
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
"""Subprocess test runner, guards, and self-healing retry loop."""
|
|
2
|
+
|
|
3
|
+
import ast
|
|
4
|
+
import json
|
|
5
|
+
import logging
|
|
6
|
+
import re
|
|
7
|
+
import shlex
|
|
8
|
+
import shutil
|
|
9
|
+
import subprocess
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from diff2test.context_builder import build_fix_prompt, build_generation_prompt
|
|
14
|
+
from diff2test.llm_client import LLMClient, extract_code
|
|
15
|
+
from diff2test.models import Attempt, Config, GenerationResult, TestContext
|
|
16
|
+
from diff2test.profiles import Profile, select_profile
|
|
17
|
+
|
|
18
|
+
logger = logging.getLogger(__name__)
|
|
19
|
+
|
|
20
|
+
_ANSI_ESCAPE_RE = re.compile(r"\x1b\[[0-9;]*[mGKHF]")
|
|
21
|
+
_DEFAULT_FORBIDDEN_PATTERNS: tuple[str, ...] = ("assert True",)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class RunnerError(RuntimeError):
|
|
25
|
+
"""Raised when the test runner configuration or command is invalid."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _strip_ansi(text: str) -> str:
|
|
29
|
+
return _ANSI_ESCAPE_RE.sub("", text)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _build_command(template: str, test_path: Path | None) -> list[str]:
|
|
33
|
+
if test_path is not None:
|
|
34
|
+
raw_cmd = template.replace("{test_path}", test_path.as_posix())
|
|
35
|
+
else:
|
|
36
|
+
raw_cmd = template.replace("{test_path}", "").strip()
|
|
37
|
+
if raw_cmd.endswith("--"):
|
|
38
|
+
raw_cmd = raw_cmd[:-2].strip()
|
|
39
|
+
parts = shlex.split(raw_cmd, posix=True)
|
|
40
|
+
if not parts:
|
|
41
|
+
raise RunnerError("Resolved test command is empty.")
|
|
42
|
+
return parts
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def run_tests(
|
|
46
|
+
repo_root: Path,
|
|
47
|
+
test_path: Path | None,
|
|
48
|
+
cfg: Config,
|
|
49
|
+
*,
|
|
50
|
+
max_output_chars: int = 20_000,
|
|
51
|
+
) -> tuple[int, str]:
|
|
52
|
+
"""Run the configured test command as a subprocess and return ``(exit_code, output)``."""
|
|
53
|
+
if not cfg.test_command:
|
|
54
|
+
raise RunnerError("No test_command configured or detected.")
|
|
55
|
+
|
|
56
|
+
cmd = _build_command(cfg.test_command, test_path)
|
|
57
|
+
resolved = shutil.which(cmd[0])
|
|
58
|
+
if resolved:
|
|
59
|
+
cmd = [resolved, *cmd[1:]]
|
|
60
|
+
try:
|
|
61
|
+
completed = subprocess.run(
|
|
62
|
+
cmd,
|
|
63
|
+
cwd=repo_root,
|
|
64
|
+
capture_output=True,
|
|
65
|
+
text=True,
|
|
66
|
+
encoding="utf-8",
|
|
67
|
+
errors="replace",
|
|
68
|
+
timeout=cfg.test_timeout_sec,
|
|
69
|
+
check=False,
|
|
70
|
+
)
|
|
71
|
+
combined = "\n".join(part for part in (completed.stdout, completed.stderr) if part).strip()
|
|
72
|
+
cleaned = _strip_ansi(combined)
|
|
73
|
+
if len(cleaned) > max_output_chars:
|
|
74
|
+
cleaned = cleaned[-max_output_chars:]
|
|
75
|
+
return completed.returncode, cleaned
|
|
76
|
+
except subprocess.TimeoutExpired as exc:
|
|
77
|
+
out = ""
|
|
78
|
+
if exc.stdout:
|
|
79
|
+
out += str(exc.stdout)
|
|
80
|
+
if exc.stderr:
|
|
81
|
+
out += ("\n" if out else "") + str(exc.stderr)
|
|
82
|
+
msg = f"Test command timed out after {cfg.test_timeout_sec}s."
|
|
83
|
+
if out.strip():
|
|
84
|
+
msg = f"{msg}\n{_strip_ansi(out.strip())}"
|
|
85
|
+
return 124, msg[-max_output_chars:]
|
|
86
|
+
except FileNotFoundError as exc:
|
|
87
|
+
return 127, f"Test executable not found ({cmd[0]}): {exc}"
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class TestFileTransaction:
|
|
91
|
+
"""Context manager writing a generated test file with automatic rollback on failure."""
|
|
92
|
+
|
|
93
|
+
def __init__(
|
|
94
|
+
self,
|
|
95
|
+
repo_root: Path,
|
|
96
|
+
rel_test_path: Path,
|
|
97
|
+
*,
|
|
98
|
+
keep_on_failure: bool = False,
|
|
99
|
+
) -> None:
|
|
100
|
+
self.repo_root = repo_root
|
|
101
|
+
self.rel_test_path = rel_test_path
|
|
102
|
+
self.abs_path = repo_root / rel_test_path
|
|
103
|
+
self.keep_on_failure = keep_on_failure
|
|
104
|
+
self._created_dirs: list[Path] = []
|
|
105
|
+
self._committed = False
|
|
106
|
+
|
|
107
|
+
def __enter__(self) -> "TestFileTransaction":
|
|
108
|
+
if self.abs_path.exists():
|
|
109
|
+
raise FileExistsError(
|
|
110
|
+
f"Refusing to overwrite existing test file: {self.rel_test_path.as_posix()}"
|
|
111
|
+
)
|
|
112
|
+
missing_dirs: list[Path] = []
|
|
113
|
+
curr = self.abs_path.parent
|
|
114
|
+
while curr != self.repo_root and not curr.exists():
|
|
115
|
+
missing_dirs.append(curr)
|
|
116
|
+
curr = curr.parent
|
|
117
|
+
for directory in reversed(missing_dirs):
|
|
118
|
+
directory.mkdir(exist_ok=True)
|
|
119
|
+
self._created_dirs.append(directory)
|
|
120
|
+
return self
|
|
121
|
+
|
|
122
|
+
def write(self, content: str) -> Path:
|
|
123
|
+
"""Write ``content`` to the target test file using LF line endings."""
|
|
124
|
+
normalized = content.replace("\r\n", "\n")
|
|
125
|
+
if not normalized.endswith("\n"):
|
|
126
|
+
normalized += "\n"
|
|
127
|
+
self.abs_path.write_text(normalized, encoding="utf-8", newline="\n")
|
|
128
|
+
return self.abs_path
|
|
129
|
+
|
|
130
|
+
def commit(self) -> None:
|
|
131
|
+
"""Keep the written test file after context exit."""
|
|
132
|
+
self._committed = True
|
|
133
|
+
|
|
134
|
+
def __exit__(self, exc_type: object, exc: object, tb: object) -> None:
|
|
135
|
+
if self._committed or (self.keep_on_failure and exc_type is None):
|
|
136
|
+
return
|
|
137
|
+
if self.abs_path.is_file():
|
|
138
|
+
self.abs_path.unlink()
|
|
139
|
+
for directory in reversed(self._created_dirs):
|
|
140
|
+
if directory.is_dir() and not any(directory.iterdir()):
|
|
141
|
+
directory.rmdir()
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
_LANG_TEST_FUNC_RE: dict[str, re.Pattern[str]] = {
|
|
145
|
+
"dart": re.compile(r"\btest(?:Widgets)?\s*\("),
|
|
146
|
+
"typescript": re.compile(r"\b(?:it|test)\s*\("),
|
|
147
|
+
"javascript": re.compile(r"\b(?:it|test)\s*\("),
|
|
148
|
+
"go": re.compile(r"\bfunc\s+Test\w+\s*\("),
|
|
149
|
+
"rust": re.compile(r"#\[test\]"),
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
_LANG_ASSERTION_RE: dict[str, re.Pattern[str]] = {
|
|
153
|
+
"dart": re.compile(r"\bexpect\s*\("),
|
|
154
|
+
"typescript": re.compile(r"\b(?:expect\s*\(|assert\.)"),
|
|
155
|
+
"javascript": re.compile(r"\b(?:expect\s*\(|assert\.)"),
|
|
156
|
+
"go": re.compile(r"\bt\.(?:Error|Errorf|Fatal|Fatalf|Fail)\b|\bassert\."),
|
|
157
|
+
"rust": re.compile(r"\bassert(?:_eq|_ne)?!\s*\("),
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _count_python_tests_and_assertions(tree: ast.AST) -> tuple[int, int]:
|
|
162
|
+
test_funcs = 0
|
|
163
|
+
assertions = 0
|
|
164
|
+
for node in ast.walk(tree):
|
|
165
|
+
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name.startswith(
|
|
166
|
+
"test_"
|
|
167
|
+
):
|
|
168
|
+
test_funcs += 1
|
|
169
|
+
elif isinstance(node, ast.Assert):
|
|
170
|
+
assertions += 1
|
|
171
|
+
elif isinstance(node, ast.Call):
|
|
172
|
+
func = node.func
|
|
173
|
+
if (isinstance(func, ast.Attribute) and func.attr in {"raises", "assertRaises"}) or (
|
|
174
|
+
isinstance(func, ast.Name) and func.id.startswith("assert")
|
|
175
|
+
):
|
|
176
|
+
assertions += 1
|
|
177
|
+
return test_funcs, assertions
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def count_assertions(code: str, language: str) -> tuple[int, int]:
|
|
181
|
+
"""Return ``(test_function_count, assertion_count)`` for ``code``."""
|
|
182
|
+
if language == "python":
|
|
183
|
+
tree = ast.parse(code)
|
|
184
|
+
return _count_python_tests_and_assertions(tree)
|
|
185
|
+
|
|
186
|
+
fn_re = _LANG_TEST_FUNC_RE.get(language, re.compile(r"\btest\b", re.IGNORECASE))
|
|
187
|
+
assert_re = _LANG_ASSERTION_RE.get(language, re.compile(r"\b(?:assert|expect)\b"))
|
|
188
|
+
return len(fn_re.findall(code)), len(assert_re.findall(code))
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def check_guards(
|
|
192
|
+
code: str,
|
|
193
|
+
previous: str | None,
|
|
194
|
+
language: str,
|
|
195
|
+
*,
|
|
196
|
+
forbidden_patterns: tuple[str, ...] = (),
|
|
197
|
+
min_assertions: int = 1,
|
|
198
|
+
) -> list[str]:
|
|
199
|
+
"""Check generated test ``code`` for hollow tests, syntax errors, and weakened assertions."""
|
|
200
|
+
violations: list[str] = []
|
|
201
|
+
if not code.strip():
|
|
202
|
+
return ["generated test code is empty"]
|
|
203
|
+
|
|
204
|
+
if language == "python":
|
|
205
|
+
try:
|
|
206
|
+
tree = ast.parse(code)
|
|
207
|
+
except SyntaxError as exc:
|
|
208
|
+
return [f"python syntax error: {exc.msg}"]
|
|
209
|
+
test_funcs, assertions = _count_python_tests_and_assertions(tree)
|
|
210
|
+
else:
|
|
211
|
+
test_funcs, assertions = count_assertions(code, language)
|
|
212
|
+
|
|
213
|
+
if test_funcs < 1:
|
|
214
|
+
violations.append("no test functions found")
|
|
215
|
+
if assertions < min_assertions:
|
|
216
|
+
violations.append(f"assertion count ({assertions}) is below minimum ({min_assertions})")
|
|
217
|
+
|
|
218
|
+
patterns = tuple(dict.fromkeys((*_DEFAULT_FORBIDDEN_PATTERNS, *forbidden_patterns)))
|
|
219
|
+
for pattern in patterns:
|
|
220
|
+
if pattern and pattern in code:
|
|
221
|
+
violations.append(f"forbidden pattern detected: {pattern}")
|
|
222
|
+
|
|
223
|
+
if previous is not None:
|
|
224
|
+
try:
|
|
225
|
+
_, prev_assertions = count_assertions(previous, language)
|
|
226
|
+
except SyntaxError:
|
|
227
|
+
prev_assertions = 0
|
|
228
|
+
if assertions < prev_assertions:
|
|
229
|
+
violations.append(f"assertion count decreased from {prev_assertions} to {assertions}")
|
|
230
|
+
|
|
231
|
+
return violations
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def generate_with_healing(
|
|
235
|
+
repo_root: Path,
|
|
236
|
+
ctx: TestContext,
|
|
237
|
+
client: LLMClient,
|
|
238
|
+
cfg: Config,
|
|
239
|
+
*,
|
|
240
|
+
profile: Profile | None = None,
|
|
241
|
+
keep_failed: bool = False,
|
|
242
|
+
full_suite: bool = False,
|
|
243
|
+
) -> GenerationResult:
|
|
244
|
+
"""Generate, guard-check, and run tests with up to ``cfg.max_retries`` attempts."""
|
|
245
|
+
active_profile = profile or select_profile(cfg.framework, repo_root=repo_root)
|
|
246
|
+
rel_test_path = Path(ctx.target_test_path)
|
|
247
|
+
attempts: list[Attempt] = []
|
|
248
|
+
previous_passing_guard_code: str | None = None
|
|
249
|
+
|
|
250
|
+
with TestFileTransaction(repo_root, rel_test_path, keep_on_failure=keep_failed) as tx:
|
|
251
|
+
for attempt_no in range(1, cfg.max_retries + 1):
|
|
252
|
+
messages = (
|
|
253
|
+
build_generation_prompt(ctx)
|
|
254
|
+
if attempt_no == 1
|
|
255
|
+
else build_fix_prompt(ctx, attempts[-1])
|
|
256
|
+
)
|
|
257
|
+
raw_reply = client.complete(messages)
|
|
258
|
+
code = extract_code(raw_reply)
|
|
259
|
+
|
|
260
|
+
violations = check_guards(
|
|
261
|
+
code,
|
|
262
|
+
previous_passing_guard_code,
|
|
263
|
+
ctx.source_file.language,
|
|
264
|
+
forbidden_patterns=active_profile.forbidden_patterns,
|
|
265
|
+
min_assertions=active_profile.min_assertions,
|
|
266
|
+
)
|
|
267
|
+
|
|
268
|
+
if violations:
|
|
269
|
+
logger.info(
|
|
270
|
+
"Attempt %d/%d for %s failed guards: %s",
|
|
271
|
+
attempt_no,
|
|
272
|
+
cfg.max_retries,
|
|
273
|
+
ctx.target_test_path,
|
|
274
|
+
"; ".join(violations),
|
|
275
|
+
)
|
|
276
|
+
attempts.append(
|
|
277
|
+
Attempt(
|
|
278
|
+
number=attempt_no,
|
|
279
|
+
test_code=code,
|
|
280
|
+
exit_code=-1,
|
|
281
|
+
output="",
|
|
282
|
+
guard_violations=violations,
|
|
283
|
+
)
|
|
284
|
+
)
|
|
285
|
+
continue
|
|
286
|
+
|
|
287
|
+
previous_passing_guard_code = code
|
|
288
|
+
tx.write(code)
|
|
289
|
+
exit_code, output = run_tests(repo_root, rel_test_path, cfg)
|
|
290
|
+
|
|
291
|
+
logger.info(
|
|
292
|
+
"Attempt %d/%d for %s exited with %d",
|
|
293
|
+
attempt_no,
|
|
294
|
+
cfg.max_retries,
|
|
295
|
+
ctx.target_test_path,
|
|
296
|
+
exit_code,
|
|
297
|
+
)
|
|
298
|
+
attempts.append(
|
|
299
|
+
Attempt(
|
|
300
|
+
number=attempt_no,
|
|
301
|
+
test_code=code,
|
|
302
|
+
exit_code=exit_code,
|
|
303
|
+
output=output,
|
|
304
|
+
)
|
|
305
|
+
)
|
|
306
|
+
|
|
307
|
+
if exit_code == 127:
|
|
308
|
+
logger.warning(
|
|
309
|
+
"Aborting retries for %s: test executable not found.", ctx.target_test_path
|
|
310
|
+
)
|
|
311
|
+
break
|
|
312
|
+
|
|
313
|
+
if exit_code == 0 and full_suite:
|
|
314
|
+
suite_code, suite_out = run_tests(repo_root, None, cfg)
|
|
315
|
+
if suite_code != 0:
|
|
316
|
+
attempts[-1] = Attempt(
|
|
317
|
+
number=attempt_no,
|
|
318
|
+
test_code=code,
|
|
319
|
+
exit_code=suite_code,
|
|
320
|
+
output=f"Full suite regression check failed:\n{suite_out}",
|
|
321
|
+
)
|
|
322
|
+
continue
|
|
323
|
+
|
|
324
|
+
if exit_code == 0:
|
|
325
|
+
tx.commit()
|
|
326
|
+
return GenerationResult(
|
|
327
|
+
source_path=ctx.source_file.path,
|
|
328
|
+
test_path=ctx.target_test_path,
|
|
329
|
+
success=True,
|
|
330
|
+
attempts=attempts,
|
|
331
|
+
final_code=code,
|
|
332
|
+
)
|
|
333
|
+
|
|
334
|
+
return GenerationResult(
|
|
335
|
+
source_path=ctx.source_file.path,
|
|
336
|
+
test_path=ctx.target_test_path,
|
|
337
|
+
success=False,
|
|
338
|
+
attempts=attempts,
|
|
339
|
+
final_code=None,
|
|
340
|
+
)
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def serialize_results(results: list[GenerationResult]) -> dict[str, Any]:
|
|
344
|
+
"""Convert ``GenerationResult`` objects into a JSON-serializable summary dictionary."""
|
|
345
|
+
generated_count = sum(1 for r in results if r.success)
|
|
346
|
+
failed_count = len(results) - generated_count
|
|
347
|
+
return {
|
|
348
|
+
"total": len(results),
|
|
349
|
+
"generated_count": generated_count,
|
|
350
|
+
"failed_count": failed_count,
|
|
351
|
+
"results": [
|
|
352
|
+
{
|
|
353
|
+
"source_path": r.source_path,
|
|
354
|
+
"test_path": r.test_path,
|
|
355
|
+
"success": r.success,
|
|
356
|
+
"final_code": r.final_code,
|
|
357
|
+
"attempts": [
|
|
358
|
+
{
|
|
359
|
+
"number": a.number,
|
|
360
|
+
"exit_code": a.exit_code,
|
|
361
|
+
"output": a.output,
|
|
362
|
+
"guard_violations": list(a.guard_violations),
|
|
363
|
+
}
|
|
364
|
+
for a in r.attempts
|
|
365
|
+
],
|
|
366
|
+
}
|
|
367
|
+
for r in results
|
|
368
|
+
],
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def write_report(
|
|
373
|
+
repo_root: Path,
|
|
374
|
+
results: list[GenerationResult],
|
|
375
|
+
report_path: Path | None = None,
|
|
376
|
+
) -> Path:
|
|
377
|
+
"""Write structured JSON run report to ``.diff2test/report.json`` (or ``report_path``)."""
|
|
378
|
+
target = report_path or (repo_root / ".diff2test" / "report.json")
|
|
379
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
380
|
+
payload = serialize_results(results)
|
|
381
|
+
target.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8", newline="\n")
|
|
382
|
+
return target
|
diff2test/summary.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""Summary formatting helpers for test generation results."""
|
|
2
|
+
|
|
3
|
+
from diff2test.models import GenerationResult
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def count_results(results: list[GenerationResult]) -> tuple[int, int]:
|
|
7
|
+
"""Return ``(passed, failed)`` counts for ``results``."""
|
|
8
|
+
passed = sum(1 for res in results if res.success)
|
|
9
|
+
failed = len(results) - passed
|
|
10
|
+
return passed, failed
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def format_summary_line(results: list[GenerationResult]) -> str:
|
|
14
|
+
"""Format a one-line human-readable summary for ``results``."""
|
|
15
|
+
if not results:
|
|
16
|
+
return "No eligible changed source files found in diff."
|
|
17
|
+
passed, failed = count_results(results)
|
|
18
|
+
return f"Summary: {passed} passed, {failed} failed (total {len(results)})."
|
diff2test/symbols.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""Extract changed function and class symbols from source files."""
|
|
2
|
+
|
|
3
|
+
import ast
|
|
4
|
+
import re
|
|
5
|
+
|
|
6
|
+
_NON_PYTHON_PATTERNS: dict[str, tuple[re.Pattern[str], ...]] = {
|
|
7
|
+
"go": (re.compile(r"^\s*func\s+(?:\([^)]*\)\s*)?([A-Za-z_]\w*)\s*\("),),
|
|
8
|
+
"rust": (
|
|
9
|
+
re.compile(r"^\s*(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?fn\s+([A-Za-z_]\w*)\s*[<(]"),
|
|
10
|
+
re.compile(r"^\s*(?:pub(?:\([^)]*\))?\s+)?struct\s+([A-Za-z_]\w*)"),
|
|
11
|
+
),
|
|
12
|
+
"typescript": (
|
|
13
|
+
re.compile(r"^\s*(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*[<(]"),
|
|
14
|
+
re.compile(r"^\s*(?:export\s+)?class\s+([A-Za-z_$][\w$]*)"),
|
|
15
|
+
),
|
|
16
|
+
"javascript": (
|
|
17
|
+
re.compile(r"^\s*(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\("),
|
|
18
|
+
re.compile(r"^\s*(?:export\s+)?class\s+([A-Za-z_$][\w$]*)"),
|
|
19
|
+
),
|
|
20
|
+
"dart": (
|
|
21
|
+
re.compile(r"^\s*(?:abstract\s+)?class\s+([A-Za-z_]\w*)"),
|
|
22
|
+
re.compile(
|
|
23
|
+
r"^\s*(?:[\w<>?]+\s+)+([A-Za-z_]\w*)\s*\([^;]*\)\s*(?:async\s*)?\{",
|
|
24
|
+
),
|
|
25
|
+
),
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _extract_python_symbols(source_code: str, changed_lines: set[int]) -> tuple[str, ...]:
|
|
30
|
+
try:
|
|
31
|
+
tree = ast.parse(source_code)
|
|
32
|
+
except SyntaxError:
|
|
33
|
+
return ()
|
|
34
|
+
|
|
35
|
+
found: list[str] = []
|
|
36
|
+
|
|
37
|
+
def _visit(node: ast.AST, class_prefix: str | None = None) -> None:
|
|
38
|
+
for child in ast.iter_child_nodes(node):
|
|
39
|
+
if isinstance(child, ast.ClassDef):
|
|
40
|
+
start = getattr(child, "lineno", 0)
|
|
41
|
+
end = getattr(child, "end_lineno", start)
|
|
42
|
+
if any(start <= line <= end for line in changed_lines):
|
|
43
|
+
before_len = len(found)
|
|
44
|
+
_visit(child, class_prefix=child.name)
|
|
45
|
+
if len(found) == before_len:
|
|
46
|
+
found.append(child.name)
|
|
47
|
+
elif isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
48
|
+
start = getattr(child, "lineno", 0)
|
|
49
|
+
end = getattr(child, "end_lineno", start)
|
|
50
|
+
if any(start <= line <= end for line in changed_lines):
|
|
51
|
+
name = f"{class_prefix}.{child.name}" if class_prefix else child.name
|
|
52
|
+
if name not in found:
|
|
53
|
+
found.append(name)
|
|
54
|
+
|
|
55
|
+
_visit(tree)
|
|
56
|
+
return tuple(found)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _extract_regex_symbols(
|
|
60
|
+
source_code: str,
|
|
61
|
+
changed_lines: set[int],
|
|
62
|
+
patterns: tuple[re.Pattern[str], ...],
|
|
63
|
+
) -> tuple[str, ...]:
|
|
64
|
+
lines = source_code.splitlines()
|
|
65
|
+
found: list[str] = []
|
|
66
|
+
|
|
67
|
+
for line_no in sorted(changed_lines):
|
|
68
|
+
if line_no < 1 or line_no > len(lines):
|
|
69
|
+
continue
|
|
70
|
+
for idx in range(line_no - 1, -1, -1):
|
|
71
|
+
text = lines[idx]
|
|
72
|
+
matched_name: str | None = None
|
|
73
|
+
for pattern in patterns:
|
|
74
|
+
match = pattern.match(text)
|
|
75
|
+
if match:
|
|
76
|
+
matched_name = match.group(1)
|
|
77
|
+
break
|
|
78
|
+
if matched_name:
|
|
79
|
+
if matched_name not in found:
|
|
80
|
+
found.append(matched_name)
|
|
81
|
+
break
|
|
82
|
+
|
|
83
|
+
return tuple(found)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def extract_changed_symbols(
|
|
87
|
+
source_code: str,
|
|
88
|
+
changed_lines: set[int],
|
|
89
|
+
language: str,
|
|
90
|
+
) -> tuple[str, ...]:
|
|
91
|
+
"""Return function/class names enclosing any line in ``changed_lines``."""
|
|
92
|
+
if not source_code or not changed_lines:
|
|
93
|
+
return ()
|
|
94
|
+
if language == "python":
|
|
95
|
+
return _extract_python_symbols(source_code, changed_lines)
|
|
96
|
+
patterns = _NON_PYTHON_PATTERNS.get(language)
|
|
97
|
+
if not patterns:
|
|
98
|
+
return ()
|
|
99
|
+
return _extract_regex_symbols(source_code, changed_lines, patterns)
|