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/__init__.py
ADDED
diff2test/__main__.py
ADDED
diff2test/cli.py
ADDED
|
@@ -0,0 +1,393 @@
|
|
|
1
|
+
"""CLI entry point for diff2test."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import logging
|
|
5
|
+
import os
|
|
6
|
+
import subprocess
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Annotated
|
|
9
|
+
|
|
10
|
+
import typer
|
|
11
|
+
|
|
12
|
+
from diff2test import __version__
|
|
13
|
+
from diff2test.config import CONFIG_FILENAME, ConfigError, detect_framework, load_config
|
|
14
|
+
from diff2test.git_handler import GitError, get_repo_root
|
|
15
|
+
from diff2test.github_api import (
|
|
16
|
+
GitHubAPIError,
|
|
17
|
+
load_pr_context,
|
|
18
|
+
post_or_update_error_comment,
|
|
19
|
+
publish_pr_results,
|
|
20
|
+
render_pr_comment,
|
|
21
|
+
should_skip,
|
|
22
|
+
)
|
|
23
|
+
from diff2test.llm_client import LLMError
|
|
24
|
+
from diff2test.pipeline import collect_changes, run_pipeline
|
|
25
|
+
from diff2test.profiles import ProfileError, select_profile
|
|
26
|
+
from diff2test.runner import RunnerError, serialize_results
|
|
27
|
+
|
|
28
|
+
app = typer.Typer(
|
|
29
|
+
name="diff2test",
|
|
30
|
+
help="Diff-driven, style-cloning, self-healing unit test generator.",
|
|
31
|
+
no_args_is_help=True,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _version_callback(value: bool) -> None:
|
|
36
|
+
if value:
|
|
37
|
+
typer.echo(f"diff2test {__version__}")
|
|
38
|
+
raise typer.Exit()
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@app.callback(invoke_without_command=True)
|
|
42
|
+
def main(
|
|
43
|
+
version: bool | None = typer.Option(
|
|
44
|
+
None,
|
|
45
|
+
"--version",
|
|
46
|
+
"-V",
|
|
47
|
+
callback=_version_callback,
|
|
48
|
+
is_eager=True,
|
|
49
|
+
help="Show version and exit.",
|
|
50
|
+
),
|
|
51
|
+
) -> None:
|
|
52
|
+
"""Generate and verify unit tests from git diffs."""
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _configure_logging(verbose: bool) -> None:
|
|
56
|
+
level = logging.DEBUG if verbose else logging.WARNING
|
|
57
|
+
logging.basicConfig(level=level, format="%(levelname)s %(name)s: %(message)s")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _print_summary(results: list, *, json_output: bool) -> None:
|
|
61
|
+
if json_output:
|
|
62
|
+
typer.echo(json.dumps(serialize_results(results), indent=2))
|
|
63
|
+
return
|
|
64
|
+
|
|
65
|
+
if not results:
|
|
66
|
+
typer.echo("No eligible changed source files found in diff.")
|
|
67
|
+
return
|
|
68
|
+
|
|
69
|
+
for res in results:
|
|
70
|
+
status = "PASS" if res.success else "FAIL"
|
|
71
|
+
tries = len(res.attempts)
|
|
72
|
+
typer.echo(f"[{status}] {res.source_path} -> {res.test_path} (attempts: {tries})")
|
|
73
|
+
|
|
74
|
+
passed = sum(1 for r in results if r.success)
|
|
75
|
+
failed = len(results) - passed
|
|
76
|
+
typer.echo(f"Summary: {passed} passed, {failed} failed (total {len(results)}).")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@app.command()
|
|
80
|
+
def generate(
|
|
81
|
+
base: str | None = typer.Option(None, "--base", help="Base git ref (default: origin/main)."),
|
|
82
|
+
head: str = typer.Option("HEAD", "--head", help="Head git ref."),
|
|
83
|
+
provider: str | None = typer.Option(None, "--provider", help="LLM provider name."),
|
|
84
|
+
model: str | None = typer.Option(None, "--model", help="LLM model identifier."),
|
|
85
|
+
max_files: int | None = typer.Option(None, "--max-files", help="Max files per run."),
|
|
86
|
+
max_retries: int | None = typer.Option(None, "--max-retries", help="Max self-healing tries."),
|
|
87
|
+
test_command: str | None = typer.Option(None, "--test-command", help="Override test command."),
|
|
88
|
+
profile: str | None = typer.Option(None, "--profile", help="Profile name."),
|
|
89
|
+
dry_run: bool = typer.Option(False, "--dry-run", help="Plan without calling LLM."),
|
|
90
|
+
keep_failed: bool = typer.Option(False, "--keep-failed", help="Keep failed test files."),
|
|
91
|
+
full_suite: bool = typer.Option(False, "--full-suite", help="Run full test suite check."),
|
|
92
|
+
verbose: bool = typer.Option(False, "--verbose", "-v", help="Enable debug logging."),
|
|
93
|
+
json_output: bool = typer.Option(False, "--json", help="Emit JSON output."),
|
|
94
|
+
repo: Annotated[
|
|
95
|
+
Path | None, typer.Option("--repo", help="Path inside target git repository.")
|
|
96
|
+
] = None,
|
|
97
|
+
) -> None:
|
|
98
|
+
"""Analyze git diff and generate verified unit tests."""
|
|
99
|
+
_configure_logging(verbose)
|
|
100
|
+
|
|
101
|
+
try:
|
|
102
|
+
repo_root = get_repo_root((repo or Path(".")).resolve())
|
|
103
|
+
overrides = {
|
|
104
|
+
"base_ref": base,
|
|
105
|
+
"provider": provider,
|
|
106
|
+
"model": model,
|
|
107
|
+
"max_files": max_files,
|
|
108
|
+
"max_retries": max_retries,
|
|
109
|
+
"test_command": test_command,
|
|
110
|
+
"profile": profile,
|
|
111
|
+
}
|
|
112
|
+
cfg = load_config(repo_root, overrides=overrides)
|
|
113
|
+
results = run_pipeline(
|
|
114
|
+
repo_root,
|
|
115
|
+
cfg,
|
|
116
|
+
head_ref=head,
|
|
117
|
+
dry_run=dry_run,
|
|
118
|
+
keep_failed=keep_failed,
|
|
119
|
+
full_suite=full_suite,
|
|
120
|
+
)
|
|
121
|
+
except (ConfigError, ProfileError, GitError, RunnerError) as exc:
|
|
122
|
+
typer.echo(f"Error: {exc}", err=True)
|
|
123
|
+
raise typer.Exit(code=2) from exc
|
|
124
|
+
except LLMError as exc:
|
|
125
|
+
typer.echo(f"LLM error: {exc}", err=True)
|
|
126
|
+
raise typer.Exit(code=3) from exc
|
|
127
|
+
|
|
128
|
+
_print_summary(results, json_output=json_output)
|
|
129
|
+
if any(not r.success for r in results):
|
|
130
|
+
raise typer.Exit(code=1)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
@app.command()
|
|
134
|
+
def detect(
|
|
135
|
+
base: str | None = typer.Option(None, "--base", help="Base git ref."),
|
|
136
|
+
head: str = typer.Option("HEAD", "--head", help="Head git ref."),
|
|
137
|
+
json_output: bool = typer.Option(False, "--json", help="Emit JSON output."),
|
|
138
|
+
repo: Annotated[
|
|
139
|
+
Path | None, typer.Option("--repo", help="Path inside target git repository.")
|
|
140
|
+
] = None,
|
|
141
|
+
) -> None:
|
|
142
|
+
"""Show auto-detected framework, config, profile, and eligible diff files."""
|
|
143
|
+
try:
|
|
144
|
+
repo_root = get_repo_root((repo or Path(".")).resolve())
|
|
145
|
+
cfg = load_config(repo_root, overrides={"base_ref": base})
|
|
146
|
+
profile = (
|
|
147
|
+
cfg.profile
|
|
148
|
+
if cfg.profile and cfg.profile != "auto"
|
|
149
|
+
else select_profile(cfg.framework, repo_root=repo_root).name
|
|
150
|
+
)
|
|
151
|
+
changes = collect_changes(repo_root, cfg, head_ref=head)
|
|
152
|
+
except (ConfigError, ProfileError, GitError) as exc:
|
|
153
|
+
typer.echo(f"Error: {exc}", err=True)
|
|
154
|
+
raise typer.Exit(code=2) from exc
|
|
155
|
+
|
|
156
|
+
payload = {
|
|
157
|
+
"repo_root": str(repo_root),
|
|
158
|
+
"framework": cfg.framework,
|
|
159
|
+
"test_command": cfg.test_command,
|
|
160
|
+
"profile": profile,
|
|
161
|
+
"provider": cfg.provider,
|
|
162
|
+
"model": cfg.model,
|
|
163
|
+
"files": [
|
|
164
|
+
{
|
|
165
|
+
"path": c.path,
|
|
166
|
+
"status": c.status,
|
|
167
|
+
"language": c.language,
|
|
168
|
+
"symbols": list(c.changed_symbols),
|
|
169
|
+
}
|
|
170
|
+
for c in changes
|
|
171
|
+
],
|
|
172
|
+
}
|
|
173
|
+
if json_output:
|
|
174
|
+
typer.echo(json.dumps(payload, indent=2))
|
|
175
|
+
return
|
|
176
|
+
|
|
177
|
+
typer.echo(f"Framework: {cfg.framework or 'none'}")
|
|
178
|
+
typer.echo(f"Test command: {cfg.test_command or 'none'}")
|
|
179
|
+
typer.echo(f"Profile: {profile}")
|
|
180
|
+
typer.echo(f"Provider: {cfg.provider} ({cfg.model or 'default'})")
|
|
181
|
+
typer.echo(f"Eligible files ({len(changes)}):")
|
|
182
|
+
for c in changes:
|
|
183
|
+
syms = ", ".join(c.changed_symbols) or "-"
|
|
184
|
+
typer.echo(f" - {c.path} [{c.language}] symbols: {syms}")
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
@app.command()
|
|
188
|
+
def init(
|
|
189
|
+
force: bool = typer.Option(False, "--force", help="Overwrite existing .diff2test.yml."),
|
|
190
|
+
repo: Annotated[Path | None, typer.Option("--repo", help="Target project directory.")] = None,
|
|
191
|
+
) -> None:
|
|
192
|
+
"""Create a commented .diff2test.yml configuration file."""
|
|
193
|
+
target_dir = (repo or Path(".")).resolve()
|
|
194
|
+
config_path = target_dir / CONFIG_FILENAME
|
|
195
|
+
if config_path.exists() and not force:
|
|
196
|
+
typer.echo(
|
|
197
|
+
f"Error: {CONFIG_FILENAME} already exists (use --force to overwrite).",
|
|
198
|
+
err=True,
|
|
199
|
+
)
|
|
200
|
+
raise typer.Exit(code=2)
|
|
201
|
+
|
|
202
|
+
detected = detect_framework(target_dir)
|
|
203
|
+
framework, test_command = detected if detected else (None, "pytest {test_path}")
|
|
204
|
+
profile_name = select_profile(framework, repo_root=target_dir).name
|
|
205
|
+
|
|
206
|
+
lines = [
|
|
207
|
+
"# diff2test configuration (all fields are optional)",
|
|
208
|
+
f'test_command: "{test_command}"',
|
|
209
|
+
f"profile: {profile_name}",
|
|
210
|
+
"provider: github",
|
|
211
|
+
"# model: openai/gpt-4o-mini",
|
|
212
|
+
"base_ref: origin/main",
|
|
213
|
+
"max_files: 5",
|
|
214
|
+
"max_diff_lines: 500",
|
|
215
|
+
"max_retries: 3",
|
|
216
|
+
"# exclude:",
|
|
217
|
+
'# - "scripts/**"',
|
|
218
|
+
'# extra_instructions: "Follow project conventions."',
|
|
219
|
+
]
|
|
220
|
+
config_path.write_text("\n".join(lines) + "\n", encoding="utf-8", newline="\n")
|
|
221
|
+
typer.echo(f"Created {config_path}")
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _write_github_output(values: dict[str, str]) -> None:
|
|
225
|
+
output_path_raw = os.environ.get("GITHUB_OUTPUT", "").strip()
|
|
226
|
+
if not output_path_raw:
|
|
227
|
+
return
|
|
228
|
+
output_path = Path(output_path_raw)
|
|
229
|
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
230
|
+
with output_path.open("a", encoding="utf-8", newline="\n") as handle:
|
|
231
|
+
for key, value in values.items():
|
|
232
|
+
handle.write(f"{key}={value}\n")
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _write_step_summary(markdown: str) -> None:
|
|
236
|
+
summary_path_raw = os.environ.get("GITHUB_STEP_SUMMARY", "").strip()
|
|
237
|
+
if not summary_path_raw:
|
|
238
|
+
return
|
|
239
|
+
summary_path = Path(summary_path_raw)
|
|
240
|
+
summary_path.parent.mkdir(parents=True, exist_ok=True)
|
|
241
|
+
with summary_path.open("a", encoding="utf-8", newline="\n") as handle:
|
|
242
|
+
handle.write(markdown.rstrip("\n") + "\n")
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def _resolve_ci_base_ref(repo_root: Path, base_ref: str, base_sha: str) -> str:
|
|
246
|
+
if base_ref:
|
|
247
|
+
origin_ref = f"origin/{base_ref}"
|
|
248
|
+
check_origin = subprocess.run(
|
|
249
|
+
["git", "rev-parse", "--verify", "--quiet", origin_ref],
|
|
250
|
+
cwd=repo_root,
|
|
251
|
+
capture_output=True,
|
|
252
|
+
text=True,
|
|
253
|
+
check=False,
|
|
254
|
+
)
|
|
255
|
+
if check_origin.returncode == 0:
|
|
256
|
+
return origin_ref
|
|
257
|
+
remotes = subprocess.run(
|
|
258
|
+
["git", "remote"],
|
|
259
|
+
cwd=repo_root,
|
|
260
|
+
capture_output=True,
|
|
261
|
+
text=True,
|
|
262
|
+
check=False,
|
|
263
|
+
)
|
|
264
|
+
if "origin" in remotes.stdout.split():
|
|
265
|
+
return origin_ref
|
|
266
|
+
return base_ref
|
|
267
|
+
return base_sha or "main"
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
@app.command()
|
|
271
|
+
def ci(
|
|
272
|
+
mode: str = typer.Option("comment", "--mode", help="Result mode: 'comment' or 'commit'."),
|
|
273
|
+
provider: str | None = typer.Option(None, "--provider", help="LLM provider name."),
|
|
274
|
+
model: str | None = typer.Option(None, "--model", help="LLM model identifier."),
|
|
275
|
+
max_files: int | None = typer.Option(None, "--max-files", help="Max files per run."),
|
|
276
|
+
max_retries: int | None = typer.Option(None, "--max-retries", help="Max self-healing tries."),
|
|
277
|
+
test_command: str | None = typer.Option(None, "--test-command", help="Override test command."),
|
|
278
|
+
profile: str | None = typer.Option(None, "--profile", help="Profile name."),
|
|
279
|
+
fail_on_error: bool = typer.Option(False, "--fail-on-error", help="Fail job on errors."),
|
|
280
|
+
report_path: str = typer.Option(
|
|
281
|
+
"diff2test-report.json",
|
|
282
|
+
"--report-path",
|
|
283
|
+
help="Path for JSON report output.",
|
|
284
|
+
),
|
|
285
|
+
dry_run: bool = typer.Option(False, "--dry-run", help="Plan without calling LLM."),
|
|
286
|
+
verbose: bool = typer.Option(False, "--verbose", "-v", help="Enable debug logging."),
|
|
287
|
+
repo: Annotated[
|
|
288
|
+
Path | None, typer.Option("--repo", help="Path inside target git repository.")
|
|
289
|
+
] = None,
|
|
290
|
+
) -> None:
|
|
291
|
+
"""Run diff2test inside a GitHub Actions pull_request workflow."""
|
|
292
|
+
_configure_logging(verbose)
|
|
293
|
+
|
|
294
|
+
if mode not in {"comment", "commit"}:
|
|
295
|
+
typer.echo(
|
|
296
|
+
f"Error: invalid --mode {mode!r}; expected 'comment' or 'commit'.",
|
|
297
|
+
err=True,
|
|
298
|
+
)
|
|
299
|
+
raise typer.Exit(code=2)
|
|
300
|
+
|
|
301
|
+
try:
|
|
302
|
+
repo_root = get_repo_root((repo or Path(".")).resolve())
|
|
303
|
+
pr = load_pr_context()
|
|
304
|
+
except (GitError, GitHubAPIError) as exc:
|
|
305
|
+
typer.echo(f"Error: {exc}", err=True)
|
|
306
|
+
raise typer.Exit(code=2) from exc
|
|
307
|
+
|
|
308
|
+
report_p = Path(report_path)
|
|
309
|
+
resolved_report = report_p if report_p.is_absolute() else (repo_root / report_p)
|
|
310
|
+
skipped, reason = should_skip(actor=pr.actor, repo_root=repo_root)
|
|
311
|
+
if skipped:
|
|
312
|
+
typer.echo(reason)
|
|
313
|
+
_write_github_output(
|
|
314
|
+
{
|
|
315
|
+
"generated-count": "0",
|
|
316
|
+
"failed-count": "0",
|
|
317
|
+
"report-path": str(resolved_report),
|
|
318
|
+
}
|
|
319
|
+
)
|
|
320
|
+
_write_step_summary(f"## diff2test Report\n\n{reason}\n")
|
|
321
|
+
return
|
|
322
|
+
|
|
323
|
+
base_ref = _resolve_ci_base_ref(repo_root, pr.base_ref, pr.base_sha)
|
|
324
|
+
overrides = {
|
|
325
|
+
"base_ref": base_ref,
|
|
326
|
+
"provider": provider,
|
|
327
|
+
"model": model,
|
|
328
|
+
"max_files": max_files,
|
|
329
|
+
"max_retries": max_retries,
|
|
330
|
+
"test_command": test_command,
|
|
331
|
+
"profile": profile,
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
try:
|
|
335
|
+
cfg = load_config(repo_root, overrides=overrides)
|
|
336
|
+
results = run_pipeline(
|
|
337
|
+
repo_root,
|
|
338
|
+
cfg,
|
|
339
|
+
head_ref="HEAD",
|
|
340
|
+
dry_run=dry_run,
|
|
341
|
+
report_path=resolved_report,
|
|
342
|
+
)
|
|
343
|
+
except LLMError as exc:
|
|
344
|
+
typer.echo(f"Warning: {exc}", err=True)
|
|
345
|
+
if not dry_run and not os.environ.get("DIFF2TEST_SKIP_GITHUB_API"):
|
|
346
|
+
try:
|
|
347
|
+
post_or_update_error_comment(pr, str(exc))
|
|
348
|
+
except GitHubAPIError as api_exc:
|
|
349
|
+
typer.echo(f"Warning: failed to post PR comment: {api_exc}", err=True)
|
|
350
|
+
_write_github_output(
|
|
351
|
+
{
|
|
352
|
+
"generated-count": "0",
|
|
353
|
+
"failed-count": "0",
|
|
354
|
+
"report-path": str(resolved_report),
|
|
355
|
+
}
|
|
356
|
+
)
|
|
357
|
+
_write_step_summary(f"## diff2test Report\n\n> **Warning:** {exc}\n")
|
|
358
|
+
if fail_on_error:
|
|
359
|
+
raise typer.Exit(code=1) from exc
|
|
360
|
+
return
|
|
361
|
+
except (ConfigError, ProfileError, GitError, RunnerError) as exc:
|
|
362
|
+
typer.echo(f"Error: {exc}", err=True)
|
|
363
|
+
raise typer.Exit(code=2) from exc
|
|
364
|
+
|
|
365
|
+
resolved_report.parent.mkdir(parents=True, exist_ok=True)
|
|
366
|
+
resolved_report.write_text(
|
|
367
|
+
json.dumps(serialize_results(results), indent=2) + "\n",
|
|
368
|
+
encoding="utf-8",
|
|
369
|
+
newline="\n",
|
|
370
|
+
)
|
|
371
|
+
|
|
372
|
+
if results and not dry_run and not os.environ.get("DIFF2TEST_SKIP_GITHUB_API"):
|
|
373
|
+
try:
|
|
374
|
+
publish_pr_results(repo_root, pr, results, mode=mode)
|
|
375
|
+
except GitHubAPIError as exc:
|
|
376
|
+
typer.echo(f"Warning: failed to publish PR results: {exc}", err=True)
|
|
377
|
+
if fail_on_error:
|
|
378
|
+
raise typer.Exit(code=1) from exc
|
|
379
|
+
|
|
380
|
+
generated_count = sum(1 for r in results if r.success)
|
|
381
|
+
failed_count = len(results) - generated_count
|
|
382
|
+
_write_github_output(
|
|
383
|
+
{
|
|
384
|
+
"generated-count": str(generated_count),
|
|
385
|
+
"failed-count": str(failed_count),
|
|
386
|
+
"report-path": str(resolved_report),
|
|
387
|
+
}
|
|
388
|
+
)
|
|
389
|
+
_write_step_summary(render_pr_comment(results))
|
|
390
|
+
_print_summary(results, json_output=False)
|
|
391
|
+
|
|
392
|
+
if fail_on_error and failed_count > 0:
|
|
393
|
+
raise typer.Exit(code=1)
|
diff2test/config.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
"""Configuration loading and test framework auto-detection."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
import os
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
from dataclasses import fields
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
import yaml
|
|
11
|
+
|
|
12
|
+
from diff2test.models import Config
|
|
13
|
+
|
|
14
|
+
logger = logging.getLogger(__name__)
|
|
15
|
+
|
|
16
|
+
CONFIG_FILENAME = ".diff2test.yml"
|
|
17
|
+
VALID_OUTPUT_MODES = frozenset({"local", "commit", "comment"})
|
|
18
|
+
|
|
19
|
+
DEFAULT_EXCLUDES: tuple[str, ...] = (
|
|
20
|
+
# Lockfiles
|
|
21
|
+
"*.lock",
|
|
22
|
+
"package-lock.json",
|
|
23
|
+
"pnpm-lock.yaml",
|
|
24
|
+
"yarn.lock",
|
|
25
|
+
"pubspec.lock",
|
|
26
|
+
"poetry.lock",
|
|
27
|
+
"uv.lock",
|
|
28
|
+
"Cargo.lock",
|
|
29
|
+
"go.sum",
|
|
30
|
+
# Database migrations
|
|
31
|
+
"migrations/**",
|
|
32
|
+
"**/migrations/**",
|
|
33
|
+
# Generated files
|
|
34
|
+
"*.g.dart",
|
|
35
|
+
"*.freezed.dart",
|
|
36
|
+
"*.pb.go",
|
|
37
|
+
"*_pb2.py",
|
|
38
|
+
"*.min.js",
|
|
39
|
+
# Build, cache, and dependency directories
|
|
40
|
+
"dist/**",
|
|
41
|
+
"build/**",
|
|
42
|
+
".venv/**",
|
|
43
|
+
"node_modules/**",
|
|
44
|
+
# Existing test files and directories
|
|
45
|
+
"test/**",
|
|
46
|
+
"tests/**",
|
|
47
|
+
"**/test/**",
|
|
48
|
+
"**/tests/**",
|
|
49
|
+
"*_test.*",
|
|
50
|
+
"test_*.py",
|
|
51
|
+
"*.test.*",
|
|
52
|
+
"*.spec.*",
|
|
53
|
+
# Documentation and configuration files
|
|
54
|
+
"*.md",
|
|
55
|
+
"*.yml",
|
|
56
|
+
"*.yaml",
|
|
57
|
+
"*.toml",
|
|
58
|
+
"*.json",
|
|
59
|
+
"*.ini",
|
|
60
|
+
"*.cfg",
|
|
61
|
+
)
|
|
62
|
+
_POSITIVE_INT_FIELDS = frozenset({"max_files", "max_diff_lines", "max_retries", "test_timeout_sec"})
|
|
63
|
+
_STRING_FIELDS = frozenset(
|
|
64
|
+
{"test_command", "framework", "profile", "provider", "model", "base_ref", "extra_instructions"}
|
|
65
|
+
)
|
|
66
|
+
_KNOWN_FIELDS = frozenset(f.name for f in fields(Config))
|
|
67
|
+
|
|
68
|
+
_FRAMEWORK_RULES: tuple[tuple[tuple[str, ...], str, str], ...] = (
|
|
69
|
+
(("pubspec.yaml",), "flutter", "flutter test {test_path}"),
|
|
70
|
+
(("pyproject.toml", "pytest.ini", "setup.cfg"), "pytest", "pytest {test_path}"),
|
|
71
|
+
(("package.json",), "npm", "npm test -- {test_path}"),
|
|
72
|
+
(("go.mod",), "go", "go test ./..."),
|
|
73
|
+
(("Cargo.toml",), "cargo", "cargo test"),
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class ConfigError(ValueError):
|
|
78
|
+
"""Raised when diff2test configuration is invalid."""
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def detect_framework(repo_root: Path) -> tuple[str, str] | None:
|
|
82
|
+
"""Detect the test framework and default command from marker files in ``repo_root``."""
|
|
83
|
+
for markers, framework, command in _FRAMEWORK_RULES:
|
|
84
|
+
if any((repo_root / marker).is_file() for marker in markers):
|
|
85
|
+
return framework, command
|
|
86
|
+
return None
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _validate_positive_int(key: str, value: Any) -> int:
|
|
90
|
+
if isinstance(value, bool) or not isinstance(value, int):
|
|
91
|
+
raise ConfigError(f"Config '{key}' must be an integer, got {type(value).__name__}.")
|
|
92
|
+
if value < 1:
|
|
93
|
+
raise ConfigError(f"Config '{key}' must be >= 1, got {value}.")
|
|
94
|
+
return value
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _validate_config_values(raw: dict[str, Any], *, source: str) -> dict[str, Any]:
|
|
98
|
+
"""Validate and normalize raw configuration values, warning on unknown keys."""
|
|
99
|
+
validated: dict[str, Any] = {}
|
|
100
|
+
for key, value in raw.items():
|
|
101
|
+
if key not in _KNOWN_FIELDS:
|
|
102
|
+
logger.warning("Ignoring unknown config key '%s' in %s.", key, source)
|
|
103
|
+
continue
|
|
104
|
+
if value is None:
|
|
105
|
+
continue
|
|
106
|
+
if key in _POSITIVE_INT_FIELDS:
|
|
107
|
+
validated[key] = _validate_positive_int(key, value)
|
|
108
|
+
elif key == "exclude":
|
|
109
|
+
if not isinstance(value, (list, tuple)) or not all(
|
|
110
|
+
isinstance(item, str) for item in value
|
|
111
|
+
):
|
|
112
|
+
raise ConfigError(f"Config 'exclude' in {source} must be a list of strings.")
|
|
113
|
+
validated[key] = tuple(value)
|
|
114
|
+
elif key == "output_mode":
|
|
115
|
+
if not isinstance(value, str) or value not in VALID_OUTPUT_MODES:
|
|
116
|
+
allowed = ", ".join(sorted(VALID_OUTPUT_MODES))
|
|
117
|
+
raise ConfigError(
|
|
118
|
+
f"Config 'output_mode' must be one of ({allowed}), got {value!r}."
|
|
119
|
+
)
|
|
120
|
+
validated[key] = value
|
|
121
|
+
elif key in _STRING_FIELDS:
|
|
122
|
+
if not isinstance(value, str):
|
|
123
|
+
raise ConfigError(
|
|
124
|
+
f"Config '{key}' in {source} must be a string, got {type(value).__name__}."
|
|
125
|
+
)
|
|
126
|
+
validated[key] = value
|
|
127
|
+
return validated
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def load_yaml_config(repo_root: Path) -> dict[str, Any]:
|
|
131
|
+
"""Load and validate optional ``.diff2test.yml`` from ``repo_root``."""
|
|
132
|
+
config_path = repo_root / CONFIG_FILENAME
|
|
133
|
+
if not config_path.is_file():
|
|
134
|
+
return {}
|
|
135
|
+
|
|
136
|
+
try:
|
|
137
|
+
raw_text = config_path.read_text(encoding="utf-8")
|
|
138
|
+
data = yaml.safe_load(raw_text)
|
|
139
|
+
except (OSError, yaml.YAMLError) as exc:
|
|
140
|
+
raise ConfigError(f"Failed to parse {CONFIG_FILENAME}: {exc}") from exc
|
|
141
|
+
|
|
142
|
+
if data is None:
|
|
143
|
+
return {}
|
|
144
|
+
if not isinstance(data, dict):
|
|
145
|
+
raise ConfigError(
|
|
146
|
+
f"{CONFIG_FILENAME} root must be a YAML mapping, got {type(data).__name__}."
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
return _validate_config_values(data, source=CONFIG_FILENAME)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
_ENV_MAP: tuple[tuple[str, str], ...] = (
|
|
153
|
+
("DIFF2TEST_TEST_COMMAND", "test_command"),
|
|
154
|
+
("DIFF2TEST_FRAMEWORK", "framework"),
|
|
155
|
+
("DIFF2TEST_PROFILE", "profile"),
|
|
156
|
+
("DIFF2TEST_PROVIDER", "provider"),
|
|
157
|
+
("DIFF2TEST_MODEL", "model"),
|
|
158
|
+
("DIFF2TEST_BASE_REF", "base_ref"),
|
|
159
|
+
("DIFF2TEST_MAX_FILES", "max_files"),
|
|
160
|
+
("DIFF2TEST_MAX_DIFF_LINES", "max_diff_lines"),
|
|
161
|
+
("DIFF2TEST_MAX_RETRIES", "max_retries"),
|
|
162
|
+
("DIFF2TEST_TEST_TIMEOUT_SEC", "test_timeout_sec"),
|
|
163
|
+
("DIFF2TEST_EXCLUDE", "exclude"),
|
|
164
|
+
("DIFF2TEST_EXTRA_INSTRUCTIONS", "extra_instructions"),
|
|
165
|
+
("DIFF2TEST_OUTPUT_MODE", "output_mode"),
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def load_env_config(environ: Mapping[str, str] | None = None) -> dict[str, Any]:
|
|
170
|
+
"""Read and validate ``DIFF2TEST_*`` environment variables."""
|
|
171
|
+
env = os.environ if environ is None else environ
|
|
172
|
+
raw: dict[str, Any] = {}
|
|
173
|
+
for env_key, field_name in _ENV_MAP:
|
|
174
|
+
value = env.get(env_key)
|
|
175
|
+
if value is None or value == "":
|
|
176
|
+
continue
|
|
177
|
+
if field_name in _POSITIVE_INT_FIELDS:
|
|
178
|
+
try:
|
|
179
|
+
raw[field_name] = int(value)
|
|
180
|
+
except ValueError as exc:
|
|
181
|
+
raise ConfigError(
|
|
182
|
+
f"Environment variable {env_key} must be an integer, got {value!r}."
|
|
183
|
+
) from exc
|
|
184
|
+
elif field_name == "exclude":
|
|
185
|
+
raw[field_name] = [part.strip() for part in value.split(",") if part.strip()]
|
|
186
|
+
else:
|
|
187
|
+
raw[field_name] = value
|
|
188
|
+
|
|
189
|
+
return _validate_config_values(raw, source="environment")
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def load_config(
|
|
193
|
+
repo_root: Path,
|
|
194
|
+
overrides: dict[str, Any] | None = None,
|
|
195
|
+
environ: Mapping[str, str] | None = None,
|
|
196
|
+
) -> Config:
|
|
197
|
+
"""Merge config layers: overrides > env > .diff2test.yml > auto-detect > defaults."""
|
|
198
|
+
merged: dict[str, Any] = {}
|
|
199
|
+
|
|
200
|
+
detected = detect_framework(repo_root)
|
|
201
|
+
if detected is not None:
|
|
202
|
+
framework, test_command = detected
|
|
203
|
+
merged["framework"] = framework
|
|
204
|
+
merged["test_command"] = test_command
|
|
205
|
+
|
|
206
|
+
merged.update(load_yaml_config(repo_root))
|
|
207
|
+
merged.update(load_env_config(environ))
|
|
208
|
+
|
|
209
|
+
if overrides:
|
|
210
|
+
validated_overrides = _validate_config_values(overrides, source="CLI overrides")
|
|
211
|
+
merged.update(validated_overrides)
|
|
212
|
+
|
|
213
|
+
return Config(**merged)
|