Download backend/app/eval/xmut.py from SevdanurGenc/LLM-Automated-Test-Generation-Agent: direct link, hf CLI and curl.
- Browser
- Download file 9.52 kB
-
https://huggingface.co/SevdanurGenc/LLM-Automated-Test-Generation-Agent/resolve/main/backend/app/eval/xmut.py
- Command line
-
hf download hf://SevdanurGenc/LLM-Automated-Test-Generation-Agent/backend/app/eval/xmut.py
-
curl -L -o xmut.py https://huggingface.co/SevdanurGenc/LLM-Automated-Test-Generation-Agent/resolve/main/backend/app/eval/xmut.py
9.52 kB
| """Harici mutasyon araçlarıyla çapraz doğrulama. | |
| Platformun kendi (sözdizimsel, düzenli ifade tabanlı) mutasyon skorunun güvenilirliğini sınamak için, ajanın | |
| ürettiği son test paketleri yerleşik araçlarla yeniden ölçülür: | |
| - Python: mutmut 2.5 (her mutant için pytest) | |
| - JavaScript / TypeScript: StrykerJS 8 (Jest koşucusu) | |
| Java (PIT) bu sürümde yoktur. Harici araçların mutasyon işleçleri farklıdır; amaç skorların birebir aynı olması | |
| değil, öğeler arası sıralamanın tutarlı olmasıdır (Spearman ρ) ve ortalama farkın raporlanmasıdır. Ajan, kendi | |
| mutantlarını hedefli mutasyon turunda gördüğü için harici araç aynı zamanda bağımsız (iyimser olmayan) bir ölçüdür. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import math | |
| import re | |
| import shutil | |
| import time | |
| from pathlib import Path | |
| from typing import Any, Callable, Optional | |
| from ..sandbox.registry import get_runner | |
| TOOLS = {"python": "mutmut", "javascript": "stryker", "typescript": "stryker"} | |
| TIMEOUT = 900 | |
| SKIP_ERRORS = ("unsupported", "no_mutants") # yeniden denenmez, araç hatası sayılmaz | |
| # Testlerde gerçek araç yerine: RUN_FN(language, code, test_code, kind, html) -> run_tool çıktısı | |
| RUN_FN: Optional[Callable[..., dict[str, Any]]] = None | |
| def supported(language: str, kind: str = "unit") -> bool: | |
| return kind != "ui" and language in TOOLS | |
| def _mutmut_cmd(test_file: str) -> str: | |
| runner = f"python -m pytest -x -q -p no:cacheprovider {test_file}" | |
| return ("mkdir -p .lta && rm -rf .mutmut-cache && " | |
| f"${{LTA_MUTMUT:-mutmut}} run --paths-to-mutate solution.py --tests-dir . --runner \"{runner}\" " | |
| "--no-progress --simple-output > .lta/mutmut.log 2>&1; " | |
| "${LTA_MUTMUT:-mutmut} junitxml > .lta/mutmut.xml 2>/dev/null; cat .lta/mutmut.log | tail -n 5") | |
| def _parse_mutmut(wd: Path) -> Optional[dict[str, Any]]: | |
| f = wd / ".lta" / "mutmut.xml" | |
| if not f.exists(): | |
| return None | |
| x = f.read_text(errors="ignore") | |
| m = re.search(r'<testsuite[^>]*errors="(\d+)"[^>]*failures="(\d+)"[^>]*tests="(\d+)"', x) | |
| if not m: | |
| return None | |
| errors, failures, tests = (int(v) for v in m.groups()) | |
| if not tests: | |
| return {"no_mutants": True} | |
| # failures = hayatta kalan mutantlar; errors = zaman aşımı/şüpheli (öldürülmüş sayılır, PIT/Stryker gibi) | |
| return {"total": tests, "survived": failures, "timeout": errors, "killed": tests - failures - errors, | |
| "score": round(100.0 * (tests - failures) / tests, 2)} | |
| def _stryker_conf(source: str) -> str: | |
| return json.dumps({ | |
| "testRunner": "jest", "jest": {"configFile": "jest.config.js", "enableFindRelatedTests": False}, | |
| "mutate": [source], "reporters": ["json"], "jsonReporter": {"fileName": ".lta/stryker.json"}, | |
| "coverageAnalysis": "off", "plugins": ["@stryker-mutator/jest-runner"], "inPlace": True, | |
| "concurrency": 2, "timeoutMS": 10000, "logLevel": "warn", "disableTypeChecks": True, | |
| }) | |
| def _parse_stryker(wd: Path) -> Optional[dict[str, Any]]: | |
| f = wd / ".lta" / "stryker.json" | |
| if not f.exists(): | |
| return None | |
| try: | |
| j = json.loads(f.read_text()) | |
| except ValueError: | |
| return None | |
| st: dict[str, int] = {} | |
| for fl in (j.get("files") or {}).values(): | |
| for m in fl.get("mutants") or []: | |
| st[m.get("status", "")] = st.get(m.get("status", ""), 0) + 1 | |
| killed, timeout = st.get("Killed", 0), st.get("Timeout", 0) | |
| survived, nocov = st.get("Survived", 0), st.get("NoCoverage", 0) | |
| valid = killed + timeout + survived + nocov | |
| if not valid: | |
| return None | |
| return {"total": valid, "killed": killed, "timeout": timeout, "survived": survived + nocov, | |
| "invalid": st.get("CompileError", 0) + st.get("RuntimeError", 0), | |
| "score": round(100.0 * (killed + timeout) / valid, 2)} | |
| def run_tool(language: str, code: str, test_code: str, kind: str = "unit", html: Optional[str] = None, | |
| extra: Optional[dict[str, str]] = None, source_name: Optional[str] = None, | |
| timeout: int = TIMEOUT) -> dict[str, Any]: | |
| """Tek bir (kod, test paketi) çiftini harici araçla ölçer.""" | |
| if not supported(language, kind): | |
| return {"ok": False, "error": "unsupported"} | |
| runner = get_runner(language, kind) | |
| wd = runner.materialize(code, test_code, kind, html, extra=extra, source_name=source_name) | |
| t0 = time.time() | |
| try: | |
| if TOOLS[language] == "mutmut": | |
| cmd = _mutmut_cmd(runner.test_filename(code, kind)) | |
| else: | |
| (wd / "stryker.conf.json").write_text(_stryker_conf(runner.source_filename(code))) | |
| tc = runner.ex.node_toolchain | |
| cmd = (f"mkdir -p .lta && ln -sfn {tc}/node_modules node_modules && " | |
| "node node_modules/@stryker-mutator/core/bin/stryker.js run stryker.conf.json 2>&1 | tail -n 20") | |
| res = runner.ex.run(cmd, wd, timeout, runner.image()) | |
| parsed = _parse_mutmut(wd) if TOOLS[language] == "mutmut" else _parse_stryker(wd) | |
| out: dict[str, Any] = {"tool": TOOLS[language], "seconds": round(time.time() - t0, 1)} | |
| if parsed and parsed.get("no_mutants"): | |
| return {"ok": False, **out, "error": "no_mutants"} | |
| if parsed: | |
| return {"ok": True, **out, **parsed} | |
| if TOOLS[language] == "mutmut" and "Checking mutants" in (res.combined or "") and not res.timed_out \ | |
| and "Traceback" not in (res.combined or ""): | |
| return {"ok": False, **out, "error": "no_mutants"} | |
| txt = res.combined or "" | |
| err = "timeout" if res.timed_out else (txt if len(txt) <= 1500 else txt[:500] + "\n…\n" + txt[-1000:]) or "no result" | |
| return {"ok": False, **out, "error": err} | |
| finally: | |
| shutil.rmtree(wd, ignore_errors=True) | |
| # ------------------------------------------------------------------ değerlendirme üzerinde toplu ölçüm | |
| def check_eval(ev, out_file: Path, should_stop: Callable[[], bool] = lambda: False, | |
| manifest: Optional[dict[str, dict[str, Any]]] = None, retry_failed: bool = False) -> list[dict[str, Any]]: | |
| """Bir değerlendirmenin tamamlanmış öğelerini harici araçla ölçer. Sonuçlar öğe öğe dosyaya yazılır; | |
| yarıda kalırsa kaldığı yerden sürer.""" | |
| from .. import store | |
| from . import benchmark | |
| manifest = manifest or {i["id"]: i for i in benchmark.load_manifest()} | |
| rows: list[dict[str, Any]] = json.loads(out_file.read_text()) if out_file.exists() else [] | |
| if retry_failed: # araç hatasıyla kalan ölçümler yeniden denenir | |
| rows = [r for r in rows if r.get("ok") or r.get("error") in SKIP_ERRORS] | |
| done = {(r["item"], r["rep"]) for r in rows} | |
| for it in ev.items: | |
| if should_stop(): | |
| break | |
| if (it.id, it.rep) in done or it.status != "done" or not supported(it.language, it.kind) or not it.tests: | |
| continue | |
| job = store.get(it.job_id) if it.job_id else None | |
| src = manifest.get(it.id) | |
| if not job or not job.result or not job.result.test_code or not src: | |
| continue | |
| r = (RUN_FN or run_tool)(it.language, src["code"], job.result.test_code, it.kind, src.get("html")) | |
| rows.append({"item": it.id, "rep": it.rep, "language": it.language, "split": it.split, | |
| "ours": it.mutation_score, "ours_pre": it.mutation_score_pre, **r}) | |
| out_file.parent.mkdir(parents=True, exist_ok=True) | |
| out_file.write_text(json.dumps(rows, ensure_ascii=False, indent=1)) | |
| return rows | |
| def _rank(xs: list[float]) -> list[float]: | |
| order = sorted(range(len(xs)), key=lambda i: xs[i]) | |
| ranks = [0.0] * len(xs) | |
| i = 0 | |
| while i < len(order): | |
| j = i | |
| while j + 1 < len(order) and xs[order[j + 1]] == xs[order[i]]: | |
| j += 1 | |
| for k in range(i, j + 1): | |
| ranks[order[k]] = (i + j) / 2 + 1 | |
| i = j + 1 | |
| return ranks | |
| def _pearson(a: list[float], b: list[float]) -> Optional[float]: | |
| n = len(a) | |
| if n < 3: | |
| return None | |
| ma, mb = sum(a) / n, sum(b) / n | |
| va = sum((x - ma) ** 2 for x in a) | |
| vb = sum((y - mb) ** 2 for y in b) | |
| if va == 0 or vb == 0: | |
| return None | |
| return round(sum((x - ma) * (y - mb) for x, y in zip(a, b)) / math.sqrt(va * vb), 3) | |
| def summarize(rows: list[dict[str, Any]]) -> dict[str, Any]: | |
| """Kendi skorumuz ile harici aracın skoru: ortalamalar, ortalama fark, Spearman ρ ve Pearson r.""" | |
| ok = [r for r in rows if r.get("ok") and r.get("ours") is not None] | |
| def block(rs: list[dict[str, Any]]) -> dict[str, Any]: | |
| if not rs: | |
| return {"n": 0} | |
| a = [float(r["ours"]) for r in rs] | |
| b = [float(r["score"]) for r in rs] | |
| return {"n": len(rs), "ours": round(sum(a) / len(a), 2), "tool": round(sum(b) / len(b), 2), | |
| "diff": round(sum(x - y for x, y in zip(a, b)) / len(rs), 2), | |
| "spearman": _pearson(_rank(a), _rank(b)), "pearson": _pearson(a, b)} | |
| by_lang = {} | |
| for lang in sorted({r["language"] for r in ok}): | |
| by_lang[lang] = block([r for r in ok if r["language"] == lang]) | |
| return {"all": block(ok), "by_language": by_lang, | |
| "failed": sum(1 for r in rows if not r.get("ok") and r.get("error") not in SKIP_ERRORS), | |
| "no_mutants": sum(1 for r in rows if r.get("error") == "no_mutants"), | |
| "tools": sorted({r.get("tool") for r in rows if r.get("tool")})} | |