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/llm_client.py
ADDED
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
"""Multi-provider LLM client abstraction."""
|
|
2
|
+
|
|
3
|
+
import contextlib
|
|
4
|
+
import importlib
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
import time
|
|
8
|
+
from collections.abc import Callable, Mapping
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from typing import Any, Protocol, runtime_checkable
|
|
11
|
+
|
|
12
|
+
import httpx
|
|
13
|
+
|
|
14
|
+
from diff2test.models import Config, Message
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class LLMError(RuntimeError):
|
|
18
|
+
"""Raised when an LLM request or client configuration fails."""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class LLMRateLimitError(LLMError):
|
|
22
|
+
"""Raised when the provider rejects requests due to rate limits or quota."""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@runtime_checkable
|
|
26
|
+
class LLMClient(Protocol):
|
|
27
|
+
"""Protocol implemented by all LLM provider clients."""
|
|
28
|
+
|
|
29
|
+
def complete(self, messages: list[Message]) -> str:
|
|
30
|
+
"""Send chat ``messages`` and return the model's text response."""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class OpenAICompatibleClient:
|
|
34
|
+
"""HTTP client for OpenAI-compatible ``/chat/completions`` endpoints."""
|
|
35
|
+
|
|
36
|
+
def __init__(
|
|
37
|
+
self,
|
|
38
|
+
*,
|
|
39
|
+
base_url: str,
|
|
40
|
+
model: str,
|
|
41
|
+
api_key: str | None = None,
|
|
42
|
+
temperature: float = 0.2,
|
|
43
|
+
timeout: float = 60.0,
|
|
44
|
+
max_attempts: int = 3,
|
|
45
|
+
transport: httpx.BaseTransport | None = None,
|
|
46
|
+
sleep_fn: Callable[[float], None] = time.sleep,
|
|
47
|
+
) -> None:
|
|
48
|
+
self.base_url = base_url.rstrip("/")
|
|
49
|
+
self.model = model
|
|
50
|
+
self.api_key = api_key
|
|
51
|
+
self.temperature = temperature
|
|
52
|
+
self.timeout = timeout
|
|
53
|
+
self.max_attempts = max(1, max_attempts)
|
|
54
|
+
self._transport = transport
|
|
55
|
+
self._sleep = sleep_fn
|
|
56
|
+
|
|
57
|
+
def complete(self, messages: list[Message]) -> str:
|
|
58
|
+
"""Send chat completion request with exponential backoff on 429/5xx."""
|
|
59
|
+
url = f"{self.base_url}/chat/completions"
|
|
60
|
+
headers: dict[str, str] = {"Content-Type": "application/json"}
|
|
61
|
+
if self.api_key:
|
|
62
|
+
headers["Authorization"] = f"Bearer {self.api_key}"
|
|
63
|
+
|
|
64
|
+
payload: dict[str, Any] = {
|
|
65
|
+
"model": self.model,
|
|
66
|
+
"temperature": self.temperature,
|
|
67
|
+
"messages": [{"role": m.role, "content": m.content} for m in messages],
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
last_error: Exception | None = None
|
|
71
|
+
with httpx.Client(
|
|
72
|
+
timeout=self.timeout,
|
|
73
|
+
transport=self._transport,
|
|
74
|
+
follow_redirects=True,
|
|
75
|
+
) as client:
|
|
76
|
+
for attempt in range(1, self.max_attempts + 1):
|
|
77
|
+
try:
|
|
78
|
+
response = client.post(url, headers=headers, json=payload)
|
|
79
|
+
except httpx.TransportError as exc:
|
|
80
|
+
last_error = exc
|
|
81
|
+
if attempt < self.max_attempts:
|
|
82
|
+
self._sleep(float(2 ** (attempt - 1)))
|
|
83
|
+
continue
|
|
84
|
+
raise LLMError(f"Network error calling {url}: {exc}") from exc
|
|
85
|
+
|
|
86
|
+
if response.status_code == 429:
|
|
87
|
+
retry_after = response.headers.get("Retry-After")
|
|
88
|
+
retry_hint = f" Retry-After: {retry_after}s." if retry_after else ""
|
|
89
|
+
last_error = LLMRateLimitError(
|
|
90
|
+
f"Rate limit (429) from {url}:{retry_hint} "
|
|
91
|
+
f"Wait and retry, switch 'model', or configure a BYOK provider. "
|
|
92
|
+
f"Details: {response.text[:200]}"
|
|
93
|
+
)
|
|
94
|
+
if attempt < self.max_attempts:
|
|
95
|
+
delay = float(2 ** (attempt - 1))
|
|
96
|
+
if retry_after:
|
|
97
|
+
with contextlib.suppress(ValueError):
|
|
98
|
+
delay = min(max(float(retry_after), delay), 30.0)
|
|
99
|
+
self._sleep(delay)
|
|
100
|
+
continue
|
|
101
|
+
raise last_error
|
|
102
|
+
|
|
103
|
+
if 500 <= response.status_code < 600:
|
|
104
|
+
last_error = LLMError(
|
|
105
|
+
f"Server error ({response.status_code}) from {url}: {response.text[:200]}"
|
|
106
|
+
)
|
|
107
|
+
if attempt < self.max_attempts:
|
|
108
|
+
self._sleep(float(2 ** (attempt - 1)))
|
|
109
|
+
continue
|
|
110
|
+
raise last_error
|
|
111
|
+
|
|
112
|
+
if response.status_code >= 400:
|
|
113
|
+
raise LLMError(
|
|
114
|
+
f"LLM API error ({response.status_code}) from {url}: {response.text[:200]}"
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
try:
|
|
118
|
+
data = response.json()
|
|
119
|
+
content = data["choices"][0]["message"]["content"]
|
|
120
|
+
except (ValueError, KeyError, IndexError, TypeError) as exc:
|
|
121
|
+
raise LLMError(
|
|
122
|
+
f"Malformed LLM response payload ({response.status_code}) from {url}: "
|
|
123
|
+
f"{response.text[:300]}"
|
|
124
|
+
) from exc
|
|
125
|
+
|
|
126
|
+
if not isinstance(content, str):
|
|
127
|
+
raise LLMError(f"Expected string content in LLM response from {url}.")
|
|
128
|
+
return content
|
|
129
|
+
|
|
130
|
+
raise LLMError(f"LLM request failed: {last_error}")
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
@dataclass(frozen=True)
|
|
134
|
+
class ProviderPreset:
|
|
135
|
+
"""Default endpoint, env var, and model for a built-in provider."""
|
|
136
|
+
|
|
137
|
+
base_url: str
|
|
138
|
+
api_key_env: str | None
|
|
139
|
+
default_model: str
|
|
140
|
+
requires_api_key: bool = True
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
PROVIDER_PRESETS: dict[str, ProviderPreset] = {
|
|
144
|
+
"github": ProviderPreset(
|
|
145
|
+
base_url="https://models.github.ai/inference",
|
|
146
|
+
api_key_env="GITHUB_TOKEN",
|
|
147
|
+
default_model="openai/gpt-4o-mini",
|
|
148
|
+
),
|
|
149
|
+
"openai": ProviderPreset(
|
|
150
|
+
base_url="https://api.openai.com/v1",
|
|
151
|
+
api_key_env="OPENAI_API_KEY",
|
|
152
|
+
default_model="gpt-4o-mini",
|
|
153
|
+
),
|
|
154
|
+
"groq": ProviderPreset(
|
|
155
|
+
base_url="https://api.groq.com/openai/v1",
|
|
156
|
+
api_key_env="GROQ_API_KEY",
|
|
157
|
+
default_model="llama-3.3-70b-versatile",
|
|
158
|
+
),
|
|
159
|
+
"deepseek": ProviderPreset(
|
|
160
|
+
base_url="https://api.deepseek.com/v1",
|
|
161
|
+
api_key_env="DEEPSEEK_API_KEY",
|
|
162
|
+
default_model="deepseek-coder",
|
|
163
|
+
),
|
|
164
|
+
"ollama": ProviderPreset(
|
|
165
|
+
base_url="http://localhost:11434/v1",
|
|
166
|
+
api_key_env=None,
|
|
167
|
+
default_model="qwen2.5-coder:7b",
|
|
168
|
+
requires_api_key=False,
|
|
169
|
+
),
|
|
170
|
+
"gemini": ProviderPreset(
|
|
171
|
+
base_url="https://generativelanguage.googleapis.com/v1beta/openai",
|
|
172
|
+
api_key_env="GEMINI_API_KEY",
|
|
173
|
+
default_model="gemini-2.5-flash",
|
|
174
|
+
),
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
class LiteLLMClient:
|
|
179
|
+
"""Optional adapter delegating completions to ``litellm.completion``."""
|
|
180
|
+
|
|
181
|
+
def __init__(self, *, model: str, api_key: str | None = None, temperature: float = 0.2) -> None:
|
|
182
|
+
self.model = model
|
|
183
|
+
self.api_key = api_key
|
|
184
|
+
self.temperature = temperature
|
|
185
|
+
|
|
186
|
+
def complete(self, messages: list[Message]) -> str:
|
|
187
|
+
"""Send chat completion via ``litellm`` if installed."""
|
|
188
|
+
try:
|
|
189
|
+
litellm = importlib.import_module("litellm")
|
|
190
|
+
except ImportError as exc:
|
|
191
|
+
raise LLMError(
|
|
192
|
+
"Optional dependency 'litellm' is not installed. "
|
|
193
|
+
"Install it with: pip install 'diff-to-test[litellm]'"
|
|
194
|
+
) from exc
|
|
195
|
+
|
|
196
|
+
kwargs: dict[str, Any] = {
|
|
197
|
+
"model": self.model,
|
|
198
|
+
"temperature": self.temperature,
|
|
199
|
+
"messages": [{"role": m.role, "content": m.content} for m in messages],
|
|
200
|
+
}
|
|
201
|
+
if self.api_key:
|
|
202
|
+
kwargs["api_key"] = self.api_key
|
|
203
|
+
|
|
204
|
+
try:
|
|
205
|
+
response = litellm.completion(**kwargs)
|
|
206
|
+
content = response.choices[0].message.content
|
|
207
|
+
except Exception as exc:
|
|
208
|
+
raise LLMError(f"LiteLLM completion failed: {exc}") from exc
|
|
209
|
+
|
|
210
|
+
if not isinstance(content, str):
|
|
211
|
+
raise LLMError("LiteLLM returned non-string response content.")
|
|
212
|
+
return content
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
@dataclass
|
|
216
|
+
class StaticLLMClient:
|
|
217
|
+
"""Deterministic LLM client returning a preconfigured response (used in CI self-tests)."""
|
|
218
|
+
|
|
219
|
+
response: str
|
|
220
|
+
|
|
221
|
+
def complete(self, messages: list[Message]) -> str:
|
|
222
|
+
"""Return the configured static response."""
|
|
223
|
+
return self.response
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def resolve_default_provider(
|
|
227
|
+
configured: str | None,
|
|
228
|
+
environ: Mapping[str, str] | None = None,
|
|
229
|
+
) -> str:
|
|
230
|
+
"""Resolve the effective LLM provider, defaulting to GitHub Models."""
|
|
231
|
+
if configured and configured.strip():
|
|
232
|
+
return configured.strip().lower()
|
|
233
|
+
env = os.environ if environ is None else environ
|
|
234
|
+
if env.get("GITHUB_TOKEN"):
|
|
235
|
+
return "github"
|
|
236
|
+
return "github"
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def create_client(
|
|
240
|
+
cfg: Config,
|
|
241
|
+
*,
|
|
242
|
+
api_key: str | None = None,
|
|
243
|
+
base_url: str | None = None,
|
|
244
|
+
environ: Mapping[str, str] | None = None,
|
|
245
|
+
) -> LLMClient:
|
|
246
|
+
"""Create an ``LLMClient`` configured for ``cfg.provider``."""
|
|
247
|
+
env = os.environ if environ is None else environ
|
|
248
|
+
fake_response = env.get("DIFF2TEST_FAKE_LLM_RESPONSE", "").strip()
|
|
249
|
+
if fake_response:
|
|
250
|
+
return StaticLLMClient(fake_response)
|
|
251
|
+
|
|
252
|
+
provider = resolve_default_provider(cfg.provider, env)
|
|
253
|
+
|
|
254
|
+
if provider == "litellm":
|
|
255
|
+
resolved_key = api_key or env.get("DIFF2TEST_API_KEY") or None
|
|
256
|
+
return LiteLLMClient(model=cfg.model or "gpt-4o-mini", api_key=resolved_key)
|
|
257
|
+
|
|
258
|
+
if provider == "openai-compatible":
|
|
259
|
+
resolved_url = base_url or env.get("DIFF2TEST_BASE_URL", "")
|
|
260
|
+
if not resolved_url:
|
|
261
|
+
raise LLMError("Provider 'openai-compatible' requires base_url or DIFF2TEST_BASE_URL.")
|
|
262
|
+
resolved_key = api_key or env.get("DIFF2TEST_API_KEY") or None
|
|
263
|
+
resolved_model = cfg.model or "gpt-4o-mini"
|
|
264
|
+
return OpenAICompatibleClient(
|
|
265
|
+
base_url=resolved_url,
|
|
266
|
+
model=resolved_model,
|
|
267
|
+
api_key=resolved_key,
|
|
268
|
+
)
|
|
269
|
+
|
|
270
|
+
preset = PROVIDER_PRESETS.get(provider)
|
|
271
|
+
if preset is None:
|
|
272
|
+
raise LLMError(f"Unsupported LLM provider: {cfg.provider!r}.")
|
|
273
|
+
|
|
274
|
+
resolved_key = api_key or env.get("DIFF2TEST_API_KEY") or None
|
|
275
|
+
if not resolved_key and preset.api_key_env:
|
|
276
|
+
resolved_key = env.get(preset.api_key_env) or None
|
|
277
|
+
|
|
278
|
+
if preset.requires_api_key and not resolved_key:
|
|
279
|
+
env_hint = preset.api_key_env or "DIFF2TEST_API_KEY"
|
|
280
|
+
raise LLMError(
|
|
281
|
+
f"Missing API key for provider {provider!r}; set {env_hint} or DIFF2TEST_API_KEY."
|
|
282
|
+
)
|
|
283
|
+
|
|
284
|
+
return OpenAICompatibleClient(
|
|
285
|
+
base_url=base_url or preset.base_url,
|
|
286
|
+
model=cfg.model or preset.default_model,
|
|
287
|
+
api_key=resolved_key,
|
|
288
|
+
)
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
_FENCED_BLOCK_RE = re.compile(r"```[a-zA-Z0-9_+-]*\r?\n(.*?)```", re.DOTALL)
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def extract_code(response: str) -> str:
|
|
295
|
+
"""Extract the primary fenced code block from an LLM response."""
|
|
296
|
+
if not response or not response.strip():
|
|
297
|
+
return ""
|
|
298
|
+
blocks = [match.group(1).strip() for match in _FENCED_BLOCK_RE.finditer(response)]
|
|
299
|
+
if blocks:
|
|
300
|
+
return max(blocks, key=len)
|
|
301
|
+
return response.strip()
|
diff2test/models.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""Core data models for diff2test."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
@dataclass(frozen=True)
|
|
7
|
+
class Message:
|
|
8
|
+
"""Chat message sent to an LLM provider."""
|
|
9
|
+
|
|
10
|
+
role: str
|
|
11
|
+
content: str
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(frozen=True)
|
|
15
|
+
class Config:
|
|
16
|
+
"""Resolved runtime configuration for diff2test."""
|
|
17
|
+
|
|
18
|
+
test_command: str | None = None
|
|
19
|
+
framework: str | None = None
|
|
20
|
+
profile: str = "auto"
|
|
21
|
+
provider: str = "github"
|
|
22
|
+
model: str | None = None
|
|
23
|
+
base_ref: str = "origin/main"
|
|
24
|
+
max_files: int = 5
|
|
25
|
+
max_diff_lines: int = 500
|
|
26
|
+
max_retries: int = 3
|
|
27
|
+
test_timeout_sec: int = 300
|
|
28
|
+
exclude: tuple[str, ...] = ()
|
|
29
|
+
extra_instructions: str = ""
|
|
30
|
+
output_mode: str = "local"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True)
|
|
34
|
+
class Hunk:
|
|
35
|
+
"""Single diff hunk with added lines."""
|
|
36
|
+
|
|
37
|
+
old_start: int
|
|
38
|
+
old_len: int
|
|
39
|
+
new_start: int
|
|
40
|
+
new_len: int
|
|
41
|
+
added_lines: tuple[tuple[int, str], ...] = ()
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass(frozen=True)
|
|
45
|
+
class FileChange:
|
|
46
|
+
"""Parsed source file change extracted from git diff."""
|
|
47
|
+
|
|
48
|
+
path: str
|
|
49
|
+
status: str
|
|
50
|
+
hunks: tuple[Hunk, ...] = ()
|
|
51
|
+
language: str = ""
|
|
52
|
+
changed_symbols: tuple[str, ...] = ()
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass(frozen=True)
|
|
56
|
+
class TestContext:
|
|
57
|
+
"""Context assembled for generating or fixing tests for one file."""
|
|
58
|
+
|
|
59
|
+
source_file: FileChange
|
|
60
|
+
source_code: str
|
|
61
|
+
example_tests: tuple[tuple[str, str], ...]
|
|
62
|
+
target_test_path: str
|
|
63
|
+
profile_instructions: str
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass
|
|
67
|
+
class Attempt:
|
|
68
|
+
"""Result of a single test generation or self-healing attempt."""
|
|
69
|
+
|
|
70
|
+
number: int
|
|
71
|
+
test_code: str
|
|
72
|
+
exit_code: int
|
|
73
|
+
output: str
|
|
74
|
+
guard_violations: list[str] = field(default_factory=list)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@dataclass
|
|
78
|
+
class GenerationResult:
|
|
79
|
+
"""Final outcome of test generation for a single source file."""
|
|
80
|
+
|
|
81
|
+
source_path: str
|
|
82
|
+
test_path: str
|
|
83
|
+
success: bool
|
|
84
|
+
attempts: list[Attempt] = field(default_factory=list)
|
|
85
|
+
final_code: str | None = None
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@dataclass(frozen=True)
|
|
89
|
+
class PRContext:
|
|
90
|
+
"""Pull request metadata loaded from the GitHub Actions environment."""
|
|
91
|
+
|
|
92
|
+
repo: str
|
|
93
|
+
pr_number: int
|
|
94
|
+
base_ref: str
|
|
95
|
+
base_sha: str
|
|
96
|
+
head_ref: str
|
|
97
|
+
head_sha: str
|
|
98
|
+
head_repo: str
|
|
99
|
+
actor: str
|
|
100
|
+
token: str
|
|
101
|
+
api_url: str = "https://api.github.com"
|
|
102
|
+
|
|
103
|
+
@property
|
|
104
|
+
def is_fork(self) -> bool:
|
|
105
|
+
"""Return True when the PR head comes from a fork repository."""
|
|
106
|
+
return bool(self.head_repo and self.head_repo != self.repo)
|
diff2test/pipeline.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""End-to-end test generation pipeline shared by CLI and GitHub Actions."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
from diff2test.context_builder import build_context
|
|
6
|
+
from diff2test.git_handler import enrich_with_symbols, filter_changes, get_diff, parse_diff
|
|
7
|
+
from diff2test.llm_client import LLMClient, create_client
|
|
8
|
+
from diff2test.models import Config, FileChange, GenerationResult
|
|
9
|
+
from diff2test.profiles import load_profile, select_profile
|
|
10
|
+
from diff2test.runner import generate_with_healing, write_report
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def collect_changes(
|
|
14
|
+
repo_root: Path,
|
|
15
|
+
cfg: Config,
|
|
16
|
+
*,
|
|
17
|
+
head_ref: str = "HEAD",
|
|
18
|
+
) -> list[FileChange]:
|
|
19
|
+
"""Extract, parse, filter, and enrich changed files between base and head."""
|
|
20
|
+
diff_text = get_diff(repo_root, cfg.base_ref, head_ref)
|
|
21
|
+
parsed = parse_diff(diff_text)
|
|
22
|
+
filtered = filter_changes(parsed, cfg)
|
|
23
|
+
return enrich_with_symbols(repo_root, filtered)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def run_pipeline(
|
|
27
|
+
repo_root: Path,
|
|
28
|
+
cfg: Config,
|
|
29
|
+
*,
|
|
30
|
+
client: LLMClient | None = None,
|
|
31
|
+
head_ref: str = "HEAD",
|
|
32
|
+
dry_run: bool = False,
|
|
33
|
+
keep_failed: bool = False,
|
|
34
|
+
full_suite: bool = False,
|
|
35
|
+
report_path: Path | None = None,
|
|
36
|
+
) -> list[GenerationResult]:
|
|
37
|
+
"""Run diff analysis, context building, and self-healing test generation."""
|
|
38
|
+
changes = collect_changes(repo_root, cfg, head_ref=head_ref)
|
|
39
|
+
if not changes:
|
|
40
|
+
return []
|
|
41
|
+
|
|
42
|
+
profile = (
|
|
43
|
+
load_profile(cfg.profile, repo_root=repo_root)
|
|
44
|
+
if cfg.profile and cfg.profile != "auto"
|
|
45
|
+
else select_profile(cfg.framework, repo_root=repo_root)
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
if dry_run:
|
|
49
|
+
dry_results: list[GenerationResult] = []
|
|
50
|
+
for change in changes:
|
|
51
|
+
ctx = build_context(repo_root, change, cfg, profile=profile)
|
|
52
|
+
dry_results.append(
|
|
53
|
+
GenerationResult(
|
|
54
|
+
source_path=change.path,
|
|
55
|
+
test_path=ctx.target_test_path,
|
|
56
|
+
success=True,
|
|
57
|
+
attempts=[],
|
|
58
|
+
final_code=None,
|
|
59
|
+
)
|
|
60
|
+
)
|
|
61
|
+
return dry_results
|
|
62
|
+
|
|
63
|
+
llm = client if client is not None else create_client(cfg)
|
|
64
|
+
results: list[GenerationResult] = []
|
|
65
|
+
for change in changes:
|
|
66
|
+
ctx = build_context(repo_root, change, cfg, profile=profile)
|
|
67
|
+
result = generate_with_healing(
|
|
68
|
+
repo_root,
|
|
69
|
+
ctx,
|
|
70
|
+
llm,
|
|
71
|
+
cfg,
|
|
72
|
+
profile=profile,
|
|
73
|
+
keep_failed=keep_failed,
|
|
74
|
+
full_suite=full_suite,
|
|
75
|
+
)
|
|
76
|
+
results.append(result)
|
|
77
|
+
|
|
78
|
+
write_report(repo_root, results, report_path=report_path)
|
|
79
|
+
return results
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""Language and framework test generation profiles."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from importlib import resources
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import yaml
|
|
9
|
+
|
|
10
|
+
_FRAMEWORK_TO_PROFILE: dict[str, str] = {
|
|
11
|
+
"flutter": "dart-flutter",
|
|
12
|
+
"pytest": "python-fastapi",
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
_REQUIRED_STR_FIELDS = (
|
|
16
|
+
"name",
|
|
17
|
+
"language",
|
|
18
|
+
"framework",
|
|
19
|
+
"test_dir",
|
|
20
|
+
"test_file_pattern",
|
|
21
|
+
"instructions",
|
|
22
|
+
)
|
|
23
|
+
_REQUIRED_LIST_FIELDS = ("example_globs", "forbidden_patterns")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class ProfileError(ValueError):
|
|
27
|
+
"""Raised when a profile cannot be found or fails schema validation."""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True)
|
|
31
|
+
class Profile:
|
|
32
|
+
"""Test generation rules and patterns for a language/framework."""
|
|
33
|
+
|
|
34
|
+
name: str
|
|
35
|
+
language: str
|
|
36
|
+
framework: str
|
|
37
|
+
test_dir: str
|
|
38
|
+
test_file_pattern: str
|
|
39
|
+
example_globs: tuple[str, ...]
|
|
40
|
+
instructions: str
|
|
41
|
+
forbidden_patterns: tuple[str, ...]
|
|
42
|
+
min_assertions: int = 1
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _parse_profile_yaml(raw_text: str, *, source: str) -> Profile:
|
|
46
|
+
try:
|
|
47
|
+
data = yaml.safe_load(raw_text)
|
|
48
|
+
except yaml.YAMLError as exc:
|
|
49
|
+
raise ProfileError(f"Invalid YAML in profile {source}: {exc}") from exc
|
|
50
|
+
|
|
51
|
+
if not isinstance(data, dict):
|
|
52
|
+
raise ProfileError(f"Profile {source} must be a YAML mapping.")
|
|
53
|
+
|
|
54
|
+
kwargs: dict[str, Any] = {}
|
|
55
|
+
for field_name in _REQUIRED_STR_FIELDS:
|
|
56
|
+
val = data.get(field_name)
|
|
57
|
+
if not isinstance(val, str) or not val.strip():
|
|
58
|
+
raise ProfileError(f"Profile {source} requires non-empty string '{field_name}'.")
|
|
59
|
+
kwargs[field_name] = val
|
|
60
|
+
|
|
61
|
+
for field_name in _REQUIRED_LIST_FIELDS:
|
|
62
|
+
val = data.get(field_name)
|
|
63
|
+
if not isinstance(val, list) or not all(isinstance(item, str) for item in val):
|
|
64
|
+
raise ProfileError(f"Profile {source} requires string list '{field_name}'.")
|
|
65
|
+
kwargs[field_name] = tuple(val)
|
|
66
|
+
|
|
67
|
+
min_assertions = data.get("min_assertions", 1)
|
|
68
|
+
if (
|
|
69
|
+
isinstance(min_assertions, bool)
|
|
70
|
+
or not isinstance(min_assertions, int)
|
|
71
|
+
or min_assertions < 1
|
|
72
|
+
):
|
|
73
|
+
raise ProfileError(f"Profile {source} 'min_assertions' must be an integer >= 1.")
|
|
74
|
+
kwargs["min_assertions"] = min_assertions
|
|
75
|
+
|
|
76
|
+
return Profile(**kwargs)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _local_profiles_dir(repo_root: Path | None) -> Path | None:
|
|
80
|
+
if repo_root is None:
|
|
81
|
+
return None
|
|
82
|
+
return repo_root / ".diff2test" / "profiles"
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def load_profile(name: str, repo_root: Path | None = None) -> Profile:
|
|
86
|
+
"""Load a profile by ``name``, preferring ``.diff2test/profiles/`` over built-ins."""
|
|
87
|
+
local_dir = _local_profiles_dir(repo_root)
|
|
88
|
+
if local_dir is not None:
|
|
89
|
+
local_file = local_dir / f"{name}.yaml"
|
|
90
|
+
if local_file.is_file():
|
|
91
|
+
return _parse_profile_yaml(
|
|
92
|
+
local_file.read_text(encoding="utf-8"),
|
|
93
|
+
source=str(local_file),
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
builtin_dir = resources.files("diff2test.profiles")
|
|
97
|
+
builtin_file = builtin_dir.joinpath(f"{name}.yaml")
|
|
98
|
+
if builtin_file.is_file():
|
|
99
|
+
return _parse_profile_yaml(
|
|
100
|
+
builtin_file.read_text(encoding="utf-8"),
|
|
101
|
+
source=f"builtin:{name}.yaml",
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
raise ProfileError(f"Profile '{name}' not found.")
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def list_profiles(repo_root: Path | None = None) -> tuple[str, ...]:
|
|
108
|
+
"""Return sorted available profile names from built-ins and optional local repo."""
|
|
109
|
+
names: set[str] = set()
|
|
110
|
+
builtin_dir = resources.files("diff2test.profiles")
|
|
111
|
+
for entry in builtin_dir.iterdir():
|
|
112
|
+
if entry.is_file() and entry.name.endswith(".yaml"):
|
|
113
|
+
names.add(entry.name[:-5])
|
|
114
|
+
|
|
115
|
+
local_dir = _local_profiles_dir(repo_root)
|
|
116
|
+
if local_dir is not None and local_dir.is_dir():
|
|
117
|
+
for entry in local_dir.glob("*.yaml"):
|
|
118
|
+
names.add(entry.stem)
|
|
119
|
+
|
|
120
|
+
return tuple(sorted(names))
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def select_profile(framework: str | None, repo_root: Path | None = None) -> Profile:
|
|
124
|
+
"""Select the best matching profile for ``framework``, falling back to ``generic``."""
|
|
125
|
+
profile_name = _FRAMEWORK_TO_PROFILE.get(framework or "", "generic")
|
|
126
|
+
return load_profile(profile_name, repo_root=repo_root)
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
name: dart-flutter
|
|
2
|
+
language: dart
|
|
3
|
+
framework: flutter
|
|
4
|
+
test_dir: test
|
|
5
|
+
test_file_pattern: "{stem}_test.dart"
|
|
6
|
+
example_globs:
|
|
7
|
+
- "test/**/*_test.dart"
|
|
8
|
+
- "test/*_test.dart"
|
|
9
|
+
instructions: |
|
|
10
|
+
- Use `package:flutter_test/flutter_test.dart` (`test(...)`, `testWidgets(...)`, `group(...)`, `expect(...)`).
|
|
11
|
+
- Match the mocking library used in the example tests (`mocktail` vs `mockito`); never mix both.
|
|
12
|
+
- Keep tests null-safe and test empty lists, null/missing fields, and error states alongside widget/unit happy paths.
|
|
13
|
+
- For widget tests, wrap widgets in `MaterialApp` / `Scaffold` when required and call `await tester.pumpWidget(...)`.
|
|
14
|
+
forbidden_patterns:
|
|
15
|
+
- "expect(true, isTrue)"
|
|
16
|
+
- "skip: true"
|
|
17
|
+
min_assertions: 1
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
name: generic
|
|
2
|
+
language: generic
|
|
3
|
+
framework: generic
|
|
4
|
+
test_dir: tests
|
|
5
|
+
test_file_pattern: "test_{stem}.*"
|
|
6
|
+
example_globs:
|
|
7
|
+
- "tests/**"
|
|
8
|
+
- "test/**"
|
|
9
|
+
instructions: |
|
|
10
|
+
- Mirror the test framework, mocking library, imports, and naming conventions from the provided example tests.
|
|
11
|
+
- Cover both happy paths and edge cases (null/None values, empty collections, boundary values, and error paths).
|
|
12
|
+
- Never invent or call functions, classes, or imports that do not exist in the source code.
|
|
13
|
+
- Every test must include meaningful assertions; never emit empty or trivially passing tests.
|
|
14
|
+
forbidden_patterns:
|
|
15
|
+
- "assert True"
|
|
16
|
+
- "expect(true, isTrue)"
|
|
17
|
+
min_assertions: 1
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
name: python-fastapi
|
|
2
|
+
language: python
|
|
3
|
+
framework: pytest
|
|
4
|
+
test_dir: tests
|
|
5
|
+
test_file_pattern: "test_{stem}.py"
|
|
6
|
+
example_globs:
|
|
7
|
+
- "tests/**/test_*.py"
|
|
8
|
+
- "tests/test_*.py"
|
|
9
|
+
instructions: |
|
|
10
|
+
- Use pytest style (plain functions `def test_*():` and `assert`), never `unittest.TestCase`.
|
|
11
|
+
- Use `fastapi.testclient.TestClient` for FastAPI route tests when FastAPI is present in the project.
|
|
12
|
+
- Reuse fixtures from `conftest.py` or `tmp_path` / `monkeypatch` instead of touching real external services or files.
|
|
13
|
+
- Use `pytest.raises(...)` to verify error paths, validation errors (422), and edge cases (`None`, empty inputs).
|
|
14
|
+
forbidden_patterns:
|
|
15
|
+
- "assert True"
|
|
16
|
+
- "pytest.skip"
|
|
17
|
+
- "@pytest.mark.skip"
|
|
18
|
+
- "@pytest.mark.xfail"
|
|
19
|
+
min_assertions: 1
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""Bundled prompt templates for diff2test."""
|
|
2
|
+
|
|
3
|
+
from importlib import resources
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def load_prompt(name: str) -> str:
|
|
7
|
+
"""Load a Markdown prompt template by name (e.g. ``'system'``, ``'generate'``, ``'fix'``)."""
|
|
8
|
+
template = resources.files("diff2test.prompts").joinpath(f"{name}.md")
|
|
9
|
+
if not template.is_file():
|
|
10
|
+
raise FileNotFoundError(f"Prompt template '{name}.md' not found.")
|
|
11
|
+
return template.read_text(encoding="utf-8")
|