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/github_api.py
ADDED
|
@@ -0,0 +1,408 @@
|
|
|
1
|
+
"""GitHub Actions PR context, comments, commits, and loop guards."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import logging
|
|
5
|
+
import os
|
|
6
|
+
import subprocess
|
|
7
|
+
from collections.abc import Iterable, Mapping
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
import httpx
|
|
12
|
+
|
|
13
|
+
from diff2test.git_handler import detect_language
|
|
14
|
+
from diff2test.models import GenerationResult, PRContext
|
|
15
|
+
|
|
16
|
+
logger = logging.getLogger(__name__)
|
|
17
|
+
|
|
18
|
+
COMMENT_MARKER = "<!-- diff2test-report -->"
|
|
19
|
+
GENERATED_BY_TRAILER = "Generated-By: diff2test"
|
|
20
|
+
BOT_NAME = "github-actions[bot]"
|
|
21
|
+
BOT_EMAIL = "41898282+github-actions[bot]@users.noreply.github.com"
|
|
22
|
+
DEFAULT_BOT_ACTORS: tuple[str, ...] = (BOT_NAME, "diff2test[bot]")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def is_bot_actor(
|
|
26
|
+
actor: str,
|
|
27
|
+
*,
|
|
28
|
+
bot_actors: Iterable[str] = DEFAULT_BOT_ACTORS,
|
|
29
|
+
) -> bool:
|
|
30
|
+
"""Return True when ``actor`` matches a known or configured bot actor."""
|
|
31
|
+
normalized = actor.strip().lower()
|
|
32
|
+
if not normalized:
|
|
33
|
+
return False
|
|
34
|
+
return any(normalized == bot.strip().lower() for bot in bot_actors if bot.strip())
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def is_generated_commit_message(message: str) -> bool:
|
|
38
|
+
"""Return True when ``message`` contains the ``Generated-By: diff2test`` trailer."""
|
|
39
|
+
target = GENERATED_BY_TRAILER.lower()
|
|
40
|
+
return any(line.strip().lower() == target for line in message.splitlines())
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def get_head_commit_message(repo_root: Path, ref: str = "HEAD") -> str:
|
|
44
|
+
"""Read the full commit message for ``ref`` in ``repo_root``."""
|
|
45
|
+
return _run_git_cmd(repo_root, ["log", "-1", "--format=%B", ref])
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def should_skip(
|
|
49
|
+
*,
|
|
50
|
+
actor: str | None = None,
|
|
51
|
+
environ: Mapping[str, str] | None = None,
|
|
52
|
+
bot_actors: Iterable[str] = DEFAULT_BOT_ACTORS,
|
|
53
|
+
head_commit_message: str | None = None,
|
|
54
|
+
repo_root: Path | None = None,
|
|
55
|
+
head_ref: str = "HEAD",
|
|
56
|
+
) -> tuple[bool, str]:
|
|
57
|
+
"""Return ``(True, reason)`` if the current CI run should be skipped to prevent loops."""
|
|
58
|
+
env = os.environ if environ is None else environ
|
|
59
|
+
effective_actor = (env.get("GITHUB_ACTOR", "") if actor is None else actor).strip()
|
|
60
|
+
if is_bot_actor(effective_actor, bot_actors=bot_actors):
|
|
61
|
+
return (True, f"Skipped: triggered by bot actor '{effective_actor}'.")
|
|
62
|
+
|
|
63
|
+
message = head_commit_message
|
|
64
|
+
if message is None and repo_root is not None:
|
|
65
|
+
try:
|
|
66
|
+
message = get_head_commit_message(repo_root, head_ref)
|
|
67
|
+
except GitHubAPIError as exc:
|
|
68
|
+
logger.warning("Could not inspect head commit message for loop guard: %s", exc)
|
|
69
|
+
message = ""
|
|
70
|
+
|
|
71
|
+
if message and is_generated_commit_message(message):
|
|
72
|
+
return (True, f"Skipped: head commit contains '{GENERATED_BY_TRAILER}' trailer.")
|
|
73
|
+
|
|
74
|
+
return (False, "")
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class GitHubAPIError(RuntimeError):
|
|
78
|
+
"""Raised when GitHub Actions context or REST API calls fail."""
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def load_pr_context(environ: Mapping[str, str] | None = None) -> PRContext:
|
|
82
|
+
"""Load ``PRContext`` from GitHub Actions environment variables and event JSON."""
|
|
83
|
+
env = os.environ if environ is None else environ
|
|
84
|
+
|
|
85
|
+
event_path_raw = env.get("GITHUB_EVENT_PATH", "").strip()
|
|
86
|
+
if not event_path_raw:
|
|
87
|
+
raise GitHubAPIError("GITHUB_EVENT_PATH is not set.")
|
|
88
|
+
|
|
89
|
+
event_path = Path(event_path_raw)
|
|
90
|
+
if not event_path.is_file():
|
|
91
|
+
raise GitHubAPIError(f"GitHub event payload not found: {event_path}")
|
|
92
|
+
|
|
93
|
+
try:
|
|
94
|
+
payload: dict[str, Any] = json.loads(event_path.read_text(encoding="utf-8"))
|
|
95
|
+
except (OSError, ValueError) as exc:
|
|
96
|
+
raise GitHubAPIError(f"Failed to read GitHub event payload: {exc}") from exc
|
|
97
|
+
|
|
98
|
+
pr_data = payload.get("pull_request")
|
|
99
|
+
if not isinstance(pr_data, dict):
|
|
100
|
+
raise GitHubAPIError("GitHub event payload does not contain a 'pull_request' object.")
|
|
101
|
+
|
|
102
|
+
repo = env.get("GITHUB_REPOSITORY", "").strip()
|
|
103
|
+
if not repo:
|
|
104
|
+
repo = str((payload.get("repository") or {}).get("full_name") or "").strip()
|
|
105
|
+
if not repo:
|
|
106
|
+
raise GitHubAPIError("GITHUB_REPOSITORY is not set.")
|
|
107
|
+
|
|
108
|
+
token = (env.get("GITHUB_TOKEN") or env.get("GH_TOKEN") or "").strip()
|
|
109
|
+
if not token:
|
|
110
|
+
raise GitHubAPIError("GITHUB_TOKEN is not set.")
|
|
111
|
+
|
|
112
|
+
base_info = pr_data.get("base") or {}
|
|
113
|
+
head_info = pr_data.get("head") or {}
|
|
114
|
+
head_repo = str((head_info.get("repo") or {}).get("full_name") or repo).strip()
|
|
115
|
+
|
|
116
|
+
try:
|
|
117
|
+
pr_number = int(pr_data["number"])
|
|
118
|
+
except (KeyError, TypeError, ValueError) as exc:
|
|
119
|
+
raise GitHubAPIError("Pull request payload is missing a valid 'number'.") from exc
|
|
120
|
+
|
|
121
|
+
return PRContext(
|
|
122
|
+
repo=repo,
|
|
123
|
+
pr_number=pr_number,
|
|
124
|
+
base_ref=str(base_info.get("ref") or "main"),
|
|
125
|
+
base_sha=str(base_info.get("sha") or ""),
|
|
126
|
+
head_ref=str(head_info.get("ref") or ""),
|
|
127
|
+
head_sha=str(head_info.get("sha") or ""),
|
|
128
|
+
head_repo=head_repo,
|
|
129
|
+
actor=env.get("GITHUB_ACTOR", "").strip(),
|
|
130
|
+
token=token,
|
|
131
|
+
api_url=env.get("GITHUB_API_URL", "https://api.github.com").rstrip("/"),
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
class GitHubRestClient:
|
|
136
|
+
"""Minimal GitHub REST API client for PR comments."""
|
|
137
|
+
|
|
138
|
+
def __init__(
|
|
139
|
+
self,
|
|
140
|
+
*,
|
|
141
|
+
token: str,
|
|
142
|
+
api_url: str = "https://api.github.com",
|
|
143
|
+
timeout: float = 30.0,
|
|
144
|
+
transport: httpx.BaseTransport | None = None,
|
|
145
|
+
) -> None:
|
|
146
|
+
self.api_url = api_url.rstrip("/")
|
|
147
|
+
self.token = token
|
|
148
|
+
self.timeout = timeout
|
|
149
|
+
self._transport = transport
|
|
150
|
+
|
|
151
|
+
def _headers(self) -> dict[str, str]:
|
|
152
|
+
return {
|
|
153
|
+
"Authorization": f"Bearer {self.token}",
|
|
154
|
+
"Accept": "application/vnd.github+json",
|
|
155
|
+
"X-GitHub-Api-Version": "2022-11-28",
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
def _request(
|
|
159
|
+
self,
|
|
160
|
+
method: str,
|
|
161
|
+
path: str,
|
|
162
|
+
*,
|
|
163
|
+
json_body: dict[str, Any] | None = None,
|
|
164
|
+
) -> Any:
|
|
165
|
+
url = f"{self.api_url}{path}"
|
|
166
|
+
with httpx.Client(timeout=self.timeout, transport=self._transport) as client:
|
|
167
|
+
try:
|
|
168
|
+
response = client.request(method, url, headers=self._headers(), json=json_body)
|
|
169
|
+
except httpx.TransportError as exc:
|
|
170
|
+
raise GitHubAPIError(f"GitHub API network error ({method} {url}): {exc}") from exc
|
|
171
|
+
|
|
172
|
+
is_rate_limit = response.status_code == 429 or (
|
|
173
|
+
response.status_code == 403
|
|
174
|
+
and (
|
|
175
|
+
"rate limit" in response.text.lower()
|
|
176
|
+
or response.headers.get("x-ratelimit-remaining") == "0"
|
|
177
|
+
)
|
|
178
|
+
)
|
|
179
|
+
if is_rate_limit:
|
|
180
|
+
raise GitHubAPIError(f"GitHub API rate limit exceeded ({response.status_code}).")
|
|
181
|
+
if response.status_code >= 400:
|
|
182
|
+
raise GitHubAPIError(
|
|
183
|
+
f"GitHub API error ({response.status_code} {method} {path}): {response.text[:200]}"
|
|
184
|
+
)
|
|
185
|
+
return response.json()
|
|
186
|
+
|
|
187
|
+
def list_issue_comments(self, repo: str, pr_number: int) -> list[dict[str, Any]]:
|
|
188
|
+
"""Return comments on PR ``pr_number`` in ``repo``."""
|
|
189
|
+
data = self._request("GET", f"/repos/{repo}/issues/{pr_number}/comments?per_page=100")
|
|
190
|
+
if not isinstance(data, list):
|
|
191
|
+
raise GitHubAPIError("Unexpected response from GitHub list comments API.")
|
|
192
|
+
return data
|
|
193
|
+
|
|
194
|
+
def create_issue_comment(self, repo: str, pr_number: int, body: str) -> dict[str, Any]:
|
|
195
|
+
"""Create a new comment on PR ``pr_number``."""
|
|
196
|
+
data = self._request(
|
|
197
|
+
"POST",
|
|
198
|
+
f"/repos/{repo}/issues/{pr_number}/comments",
|
|
199
|
+
json_body={"body": body},
|
|
200
|
+
)
|
|
201
|
+
return dict(data)
|
|
202
|
+
|
|
203
|
+
def update_issue_comment(self, repo: str, comment_id: int, body: str) -> dict[str, Any]:
|
|
204
|
+
"""Update an existing PR comment by ``comment_id``."""
|
|
205
|
+
data = self._request(
|
|
206
|
+
"PATCH",
|
|
207
|
+
f"/repos/{repo}/issues/comments/{comment_id}",
|
|
208
|
+
json_body={"body": body},
|
|
209
|
+
)
|
|
210
|
+
return dict(data)
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def render_pr_comment(results: list[GenerationResult]) -> str:
|
|
214
|
+
"""Render a Markdown PR comment summarizing test generation results."""
|
|
215
|
+
if not results:
|
|
216
|
+
return (
|
|
217
|
+
f"{COMMENT_MARKER}\n"
|
|
218
|
+
"## diff2test Report\n\n"
|
|
219
|
+
"No eligible changed source files found in diff.\n"
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
lines = [
|
|
223
|
+
COMMENT_MARKER,
|
|
224
|
+
"## diff2test Report",
|
|
225
|
+
"",
|
|
226
|
+
"| Source | Test | Status | Attempts |",
|
|
227
|
+
"|---|---|---|---|",
|
|
228
|
+
]
|
|
229
|
+
for res in results:
|
|
230
|
+
status = "PASS" if res.success else "FAIL"
|
|
231
|
+
lines.append(
|
|
232
|
+
f"| `{res.source_path}` | `{res.test_path}` | {status} | {len(res.attempts)} |"
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
passed = [r for r in results if r.success and r.final_code]
|
|
236
|
+
if passed:
|
|
237
|
+
lines.append("")
|
|
238
|
+
lines.append("### Generated Tests")
|
|
239
|
+
for res in passed:
|
|
240
|
+
lang = detect_language(res.test_path)
|
|
241
|
+
lines.extend(
|
|
242
|
+
[
|
|
243
|
+
"",
|
|
244
|
+
f"<details><summary><code>{res.test_path}</code></summary>",
|
|
245
|
+
"",
|
|
246
|
+
f"```{lang}",
|
|
247
|
+
res.final_code.strip() if res.final_code else "",
|
|
248
|
+
"```",
|
|
249
|
+
"",
|
|
250
|
+
"</details>",
|
|
251
|
+
]
|
|
252
|
+
)
|
|
253
|
+
|
|
254
|
+
failed = [r for r in results if not r.success]
|
|
255
|
+
if failed:
|
|
256
|
+
lines.append("")
|
|
257
|
+
lines.append("### Failures")
|
|
258
|
+
for res in failed:
|
|
259
|
+
last = res.attempts[-1] if res.attempts else None
|
|
260
|
+
detail = (
|
|
261
|
+
", ".join(last.guard_violations)
|
|
262
|
+
if last and last.guard_violations
|
|
263
|
+
else (last.output.splitlines()[-1] if last and last.output else "no output")
|
|
264
|
+
)
|
|
265
|
+
lines.append(f"- `{res.source_path}`: {detail}")
|
|
266
|
+
|
|
267
|
+
return "\n".join(lines) + "\n"
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def render_error_comment(message: str) -> str:
|
|
271
|
+
"""Render a Markdown PR comment explaining a non-fatal diff2test failure."""
|
|
272
|
+
lines = [
|
|
273
|
+
COMMENT_MARKER,
|
|
274
|
+
"## diff2test Report",
|
|
275
|
+
"",
|
|
276
|
+
f"> **Warning:** {message.strip()}",
|
|
277
|
+
"",
|
|
278
|
+
]
|
|
279
|
+
return "\n".join(lines)
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def _upsert_comment(
|
|
283
|
+
api: GitHubRestClient,
|
|
284
|
+
repo: str,
|
|
285
|
+
pr_number: int,
|
|
286
|
+
body: str,
|
|
287
|
+
) -> dict[str, Any]:
|
|
288
|
+
existing = api.list_issue_comments(repo, pr_number)
|
|
289
|
+
for comment in existing:
|
|
290
|
+
if COMMENT_MARKER in str(comment.get("body") or ""):
|
|
291
|
+
return api.update_issue_comment(repo, int(comment["id"]), body)
|
|
292
|
+
return api.create_issue_comment(repo, pr_number, body)
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def post_or_update_comment(
|
|
296
|
+
pr: PRContext,
|
|
297
|
+
results: list[GenerationResult],
|
|
298
|
+
*,
|
|
299
|
+
client: GitHubRestClient | None = None,
|
|
300
|
+
) -> dict[str, Any]:
|
|
301
|
+
"""Create or update the single diff2test report comment on ``pr``."""
|
|
302
|
+
api = client or GitHubRestClient(token=pr.token, api_url=pr.api_url)
|
|
303
|
+
return _upsert_comment(api, pr.repo, pr.pr_number, render_pr_comment(results))
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def post_or_update_error_comment(
|
|
307
|
+
pr: PRContext,
|
|
308
|
+
message: str,
|
|
309
|
+
*,
|
|
310
|
+
client: GitHubRestClient | None = None,
|
|
311
|
+
) -> dict[str, Any]:
|
|
312
|
+
"""Create or update the single diff2test comment with an error/rate-limit notice."""
|
|
313
|
+
api = client or GitHubRestClient(token=pr.token, api_url=pr.api_url)
|
|
314
|
+
return _upsert_comment(api, pr.repo, pr.pr_number, render_error_comment(message))
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def _run_git_cmd(repo_root: Path, args: list[str]) -> str:
|
|
318
|
+
completed = subprocess.run(
|
|
319
|
+
["git", *args],
|
|
320
|
+
cwd=repo_root,
|
|
321
|
+
capture_output=True,
|
|
322
|
+
text=True,
|
|
323
|
+
encoding="utf-8",
|
|
324
|
+
errors="replace",
|
|
325
|
+
check=False,
|
|
326
|
+
)
|
|
327
|
+
if completed.returncode != 0:
|
|
328
|
+
detail = (
|
|
329
|
+
completed.stderr.strip() or completed.stdout.strip() or f"exit {completed.returncode}"
|
|
330
|
+
)
|
|
331
|
+
raise GitHubAPIError(f"git {' '.join(args)} failed: {detail}")
|
|
332
|
+
return completed.stdout.strip()
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def commit_and_push(
|
|
336
|
+
repo_root: Path,
|
|
337
|
+
results: list[GenerationResult],
|
|
338
|
+
*,
|
|
339
|
+
branch: str | None = None,
|
|
340
|
+
push: bool = True,
|
|
341
|
+
) -> list[str]:
|
|
342
|
+
"""Commit passing test files with bot identity and ``[skip ci]`` + trailer, then push."""
|
|
343
|
+
passing_results = [
|
|
344
|
+
res for res in results if res.success and (repo_root / res.test_path).is_file()
|
|
345
|
+
]
|
|
346
|
+
if not passing_results:
|
|
347
|
+
return []
|
|
348
|
+
|
|
349
|
+
passing_paths = [res.test_path for res in passing_results]
|
|
350
|
+
_run_git_cmd(repo_root, ["add", "--", *passing_paths])
|
|
351
|
+
staged = _run_git_cmd(repo_root, ["diff", "--cached", "--name-only"])
|
|
352
|
+
if not staged:
|
|
353
|
+
return []
|
|
354
|
+
|
|
355
|
+
if len(passing_results) == 1:
|
|
356
|
+
subject = f"test: add unit tests for {passing_results[0].source_path} [skip ci]"
|
|
357
|
+
else:
|
|
358
|
+
subject = f"test: add unit tests for {len(passing_results)} files [skip ci]"
|
|
359
|
+
|
|
360
|
+
_run_git_cmd(
|
|
361
|
+
repo_root,
|
|
362
|
+
[
|
|
363
|
+
"-c",
|
|
364
|
+
f"user.name={BOT_NAME}",
|
|
365
|
+
"-c",
|
|
366
|
+
f"user.email={BOT_EMAIL}",
|
|
367
|
+
"commit",
|
|
368
|
+
"-m",
|
|
369
|
+
subject,
|
|
370
|
+
"-m",
|
|
371
|
+
GENERATED_BY_TRAILER,
|
|
372
|
+
],
|
|
373
|
+
)
|
|
374
|
+
|
|
375
|
+
if push:
|
|
376
|
+
push_args = ["push", "origin", f"HEAD:refs/heads/{branch}"] if branch else ["push"]
|
|
377
|
+
_run_git_cmd(repo_root, push_args)
|
|
378
|
+
|
|
379
|
+
logger.info("Committed %d passing test file(s).", len(passing_paths))
|
|
380
|
+
return passing_paths
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def publish_pr_results(
|
|
384
|
+
repo_root: Path,
|
|
385
|
+
pr: PRContext,
|
|
386
|
+
results: list[GenerationResult],
|
|
387
|
+
*,
|
|
388
|
+
mode: str = "comment",
|
|
389
|
+
client: GitHubRestClient | None = None,
|
|
390
|
+
) -> str:
|
|
391
|
+
"""Publish results to a PR (``'comment'`` or ``'commit'``), falling back on forks."""
|
|
392
|
+
effective_mode = mode
|
|
393
|
+
if effective_mode == "commit" and pr.is_fork:
|
|
394
|
+
logger.warning(
|
|
395
|
+
"PR #%d is from a fork (%s); falling back from 'commit' to 'comment' mode.",
|
|
396
|
+
pr.pr_number,
|
|
397
|
+
pr.head_repo,
|
|
398
|
+
)
|
|
399
|
+
effective_mode = "comment"
|
|
400
|
+
|
|
401
|
+
if effective_mode == "commit":
|
|
402
|
+
committed = commit_and_push(repo_root, results, branch=pr.head_ref or None)
|
|
403
|
+
if committed:
|
|
404
|
+
return "commit"
|
|
405
|
+
return "comment" if post_or_update_comment(pr, results, client=client) else "noop"
|
|
406
|
+
|
|
407
|
+
post_or_update_comment(pr, results, client=client)
|
|
408
|
+
return "comment"
|