Compare commits
1 Commits
burn/659-1
...
fix/issue-
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
52e3f6a253 |
@@ -1,176 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""PR Triage Automation -- Categorize, deduplicate, report (#659)."""
|
||||
import argparse, json, os, re, sys, subprocess
|
||||
from collections import Counter, defaultdict
|
||||
from datetime import datetime
|
||||
from urllib.request import Request, urlopen
|
||||
from urllib.error import HTTPError
|
||||
|
||||
|
||||
def _token():
|
||||
t = os.environ.get("GITEA_TOKEN", "")
|
||||
if not t:
|
||||
p = os.path.expanduser("~/.config/gitea/token")
|
||||
if os.path.exists(p):
|
||||
t = open(p).read().strip()
|
||||
return t
|
||||
|
||||
|
||||
def _api(url, token, method="GET", data=None):
|
||||
h = {"Authorization": "token " + token, "Accept": "application/json"}
|
||||
body = json.dumps(data).encode() if data else None
|
||||
if data:
|
||||
h["Content-Type"] = "application/json"
|
||||
req = Request(url, data=body, headers=h, method=method)
|
||||
try:
|
||||
return json.loads(urlopen(req, timeout=30).read())
|
||||
except HTTPError:
|
||||
return None
|
||||
|
||||
|
||||
def fetch_prs(base, token, owner, repo):
|
||||
prs, page = [], 1
|
||||
while True:
|
||||
b = _api(base + "/api/v1/repos/" + owner + "/" + repo + "/pulls?state=open&limit=50&page=" + str(page), token)
|
||||
if not b:
|
||||
break
|
||||
prs.extend(b)
|
||||
if len(b) < 50:
|
||||
break
|
||||
page += 1
|
||||
return prs
|
||||
|
||||
|
||||
def fetch_issues(base, token, owner, repo):
|
||||
iss, page = {}, 1
|
||||
while True:
|
||||
b = _api(base + "/api/v1/repos/" + owner + "/" + repo + "/issues?state=open&limit=50&page=" + str(page), token)
|
||||
if not b:
|
||||
break
|
||||
for i in b:
|
||||
if "pull_request" not in i:
|
||||
iss[i["number"]] = i
|
||||
if len(b) < 50:
|
||||
break
|
||||
page += 1
|
||||
return iss
|
||||
|
||||
|
||||
def categorize(pr):
|
||||
c = (pr.get("title", "") + " " + pr.get("body", "") + " " + " ".join(l.get("name", "") for l in pr.get("labels", []))).lower()
|
||||
for kw, cat in [("training data", "training-data"), ("dpo", "training-data"), ("grpo", "training-data"),
|
||||
("fix:", "bug-fix"), ("bug", "bug-fix"), ("hotfix", "bug-fix"),
|
||||
("feat:", "feature"), ("feature", "feature"),
|
||||
("refactor", "maintenance"), ("cleanup", "maintenance"),
|
||||
("doc", "documentation"), ("test", "testing"), ("infra", "infrastructure")]:
|
||||
if kw in c:
|
||||
return cat
|
||||
return "other"
|
||||
|
||||
|
||||
def refs(pr):
|
||||
return [int(m) for m in re.findall(r"#(\d+)", pr.get("title", "") + " " + pr.get("body", ""))]
|
||||
|
||||
|
||||
def find_duplicates(prs):
|
||||
by = defaultdict(list)
|
||||
for p in prs:
|
||||
for r in refs(p):
|
||||
by[r].append(p)
|
||||
return [g for g in by.values() if len(g) > 1]
|
||||
|
||||
|
||||
def health(pr, issues):
|
||||
r = refs(pr)
|
||||
created = datetime.fromisoformat(pr["created_at"].replace("Z", "+00:00"))
|
||||
updated = datetime.fromisoformat(pr["updated_at"].replace("Z", "+00:00"))
|
||||
now = datetime.now(created.tzinfo)
|
||||
return {
|
||||
"pr": pr["number"], "title": pr["title"], "head": pr["head"]["ref"],
|
||||
"category": categorize(pr), "refs": r,
|
||||
"open": [x for x in r if x in issues], "closed": [x for x in r if x not in issues],
|
||||
"age": (now - created).days, "stale": (now - updated).days,
|
||||
"mergeable": pr.get("mergeable"), "author": pr.get("user", {}).get("login", ""),
|
||||
}
|
||||
|
||||
|
||||
def report(repo, checks, dups):
|
||||
lines = ["# PR Triage -- " + repo,
|
||||
"Generated: " + datetime.now().strftime("%Y-%m-%d %H:%M"),
|
||||
"Open PRs: " + str(len(checks)), "", "## Summary", ""]
|
||||
cats = Counter(h["category"] for h in checks)
|
||||
lines.append("| Category | Count |")
|
||||
lines.append("|----------|-------|")
|
||||
for c, n in cats.most_common():
|
||||
lines.append("| " + c + " | " + str(n) + " |")
|
||||
stale = [h for h in checks if h["stale"] > 7]
|
||||
lines.extend(["", "Stale (>7d): " + str(len(stale)),
|
||||
"Duplicate groups: " + str(len(dups)), ""])
|
||||
if dups:
|
||||
lines.append("## Duplicates")
|
||||
for g in dups:
|
||||
rs = set()
|
||||
for p in g:
|
||||
rs.update(refs(p))
|
||||
lines.append("Issues " + ", ".join("#" + str(r) for r in sorted(rs)) + ":")
|
||||
for p in g:
|
||||
lines.append(" - #" + str(p["number"]) + ": " + p["title"])
|
||||
lines.append("")
|
||||
if stale:
|
||||
lines.append("## Stale (>7d)")
|
||||
for h in sorted(stale, key=lambda x: x["stale"], reverse=True):
|
||||
lines.append("- #" + str(h["pr"]) + ": " + h["title"] + " -- " + str(h["stale"]) + "d")
|
||||
lines.append("")
|
||||
lines.append("## All PRs")
|
||||
lines.append("| # | Title | Category | Age | Stale | Merge |")
|
||||
lines.append("|---|-------|----------|-----|-------|-------|")
|
||||
for h in sorted(checks, key=lambda x: x["pr"]):
|
||||
m = "Y" if h["mergeable"] else ("N" if h["mergeable"] is False else "?")
|
||||
s = str(h["stale"]) + "d" if h["stale"] > 7 else "-"
|
||||
lines.append("| " + str(h["pr"]) + " | " + h["title"][:50] + " | " + h["category"] +
|
||||
" | " + str(h["age"]) + "d | " + s + " | " + m + " |")
|
||||
return chr(10).join(lines)
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description="PR Triage Automation")
|
||||
p.add_argument("--base-url", default="https://forge.alexanderwhitestone.com")
|
||||
p.add_argument("--owner", default="Timmy_Foundation")
|
||||
p.add_argument("--repo", default="")
|
||||
p.add_argument("--json", action="store_true", dest="js")
|
||||
p.add_argument("--output", default="")
|
||||
a = p.parse_args()
|
||||
token = _token()
|
||||
if not token:
|
||||
print("No token"); sys.exit(1)
|
||||
repo = a.repo
|
||||
if not repo:
|
||||
try:
|
||||
remote = subprocess.check_output(["git", "remote", "get-url", "origin"], text=True).strip()
|
||||
m = re.search(r"[/:](\w[\w-]*)/(\w[\w-]*?)(?:\.git)?$", remote)
|
||||
if m:
|
||||
a.owner, repo = m.group(1), m.group(2)
|
||||
except Exception:
|
||||
pass
|
||||
if not repo:
|
||||
print("No repo specified"); sys.exit(1)
|
||||
print("Triaging " + a.owner + "/" + repo + "...", file=sys.stderr)
|
||||
prs = fetch_prs(a.base_url, token, a.owner, repo)
|
||||
issues = fetch_issues(a.base_url, token, a.owner, repo)
|
||||
checks = [health(pr, issues) for pr in prs]
|
||||
dups = find_duplicates(prs)
|
||||
if a.js:
|
||||
print(json.dumps({"repo": repo, "prs": checks,
|
||||
"duplicates": [[{"number": p["number"], "title": p["title"]} for p in g] for g in dups]},
|
||||
indent=2))
|
||||
else:
|
||||
r = report(repo, checks, dups)
|
||||
print(r)
|
||||
if a.output:
|
||||
with open(a.output, "w") as f:
|
||||
f.write(r)
|
||||
print("\n" + str(len(checks)) + " PRs, " + str(len(dups)) + " duplicate groups", file=sys.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,45 +0,0 @@
|
||||
"""Tests for PR triage automation (#659)."""
|
||||
import pytest
|
||||
|
||||
class TestCategorize:
|
||||
def _pr(self, title="", body=""):
|
||||
return {"title": title, "body": body, "labels": []}
|
||||
|
||||
def test_training(self):
|
||||
from scripts.pr_triage import categorize
|
||||
assert categorize(self._pr("Add DPO pairs")) == "training-data"
|
||||
|
||||
def test_bug(self):
|
||||
from scripts.pr_triage import categorize
|
||||
assert categorize(self._pr("fix: crash")) == "bug-fix"
|
||||
|
||||
def test_feature(self):
|
||||
from scripts.pr_triage import categorize
|
||||
assert categorize(self._pr("feat: dark mode")) == "feature"
|
||||
|
||||
def test_other(self):
|
||||
from scripts.pr_triage import categorize
|
||||
assert categorize(self._pr("random")) == "other"
|
||||
|
||||
class TestRefs:
|
||||
def test_simple(self):
|
||||
from scripts.pr_triage import refs
|
||||
assert 123 in refs({"title": "Fix #123", "body": ""})
|
||||
|
||||
def test_multiple(self):
|
||||
from scripts.pr_triage import refs
|
||||
r = refs({"title": "", "body": "Closes #100, Refs #200"})
|
||||
assert 100 in r and 200 in r
|
||||
|
||||
class TestDuplicates:
|
||||
def test_found(self):
|
||||
from scripts.pr_triage import find_duplicates
|
||||
prs = [{"title": "", "body": "Fix #1", "number": 1, "head": {"ref": "a"}, "created_at": "2026-01-01T00:00:00Z", "updated_at": "2026-01-01T00:00:00Z", "user": {}},
|
||||
{"title": "", "body": "Refs #1", "number": 2, "head": {"ref": "b"}, "created_at": "2026-01-01T00:00:00Z", "updated_at": "2026-01-01T00:00:00Z", "user": {}}]
|
||||
assert len(find_duplicates(prs)) == 1
|
||||
|
||||
def test_none(self):
|
||||
from scripts.pr_triage import find_duplicates
|
||||
prs = [{"title": "", "body": "Fix #1", "number": 1, "head": {"ref": "a"}, "created_at": "2026-01-01T00:00:00Z", "updated_at": "2026-01-01T00:00:00Z", "user": {}},
|
||||
{"title": "", "body": "Fix #2", "number": 2, "head": {"ref": "b"}, "created_at": "2026-01-01T00:00:00Z", "updated_at": "2026-01-01T00:00:00Z", "user": {}}]
|
||||
assert find_duplicates(prs) == []
|
||||
467
tests/test_quality_gate.py
Normal file
467
tests/test_quality_gate.py
Normal file
@@ -0,0 +1,467 @@
|
||||
"""Tests for the Quality Gate modules.
|
||||
|
||||
Tests for:
|
||||
- ci_automation_gate.py: linting, function length, auto-fix, counters
|
||||
- task_gate.py: pre/post task gate logic, lane checking, filter tags
|
||||
|
||||
Refs: #629
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch, MagicMock
|
||||
|
||||
# Add scripts/ to path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts"))
|
||||
|
||||
from ci_automation_gate import QualityGate
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# CI AUTOMATION GATE TESTS
|
||||
# ===========================================================================
|
||||
|
||||
# -- helpers ---------------------------------------------------------------
|
||||
|
||||
def _write_file(dirpath, relpath, content):
|
||||
"""Write a file in a temp directory and return its Path."""
|
||||
p = Path(dirpath) / relpath
|
||||
p.parent.mkdir(parents=True, exist_ok=True)
|
||||
p.write_text(content)
|
||||
return p
|
||||
|
||||
|
||||
def _run_gate_on_file(dirpath, relpath, content, fix=False):
|
||||
"""Write a file, run QualityGate on it, return the gate instance."""
|
||||
p = _write_file(dirpath, relpath, content)
|
||||
gate = QualityGate(fix=fix)
|
||||
gate.check_file(p)
|
||||
return gate
|
||||
|
||||
|
||||
# -- trailing whitespace ---------------------------------------------------
|
||||
|
||||
def test_trailing_whitespace_warns():
|
||||
"""Lines with trailing whitespace should produce a warning."""
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
gate = _run_gate_on_file(tmp, "test.py", "x = 1 \ny = 2\n")
|
||||
assert gate.warnings >= 1, "Expected warning for trailing whitespace"
|
||||
|
||||
|
||||
def test_trailing_whitespace_fixes():
|
||||
"""With fix=True, trailing whitespace should be removed."""
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
p = _write_file(tmp, "test.py", "x = 1 \ny = 2\n")
|
||||
gate = QualityGate(fix=True)
|
||||
gate.check_file(p)
|
||||
fixed = p.read_text()
|
||||
assert "x = 1 \n" not in fixed, "Trailing whitespace should be removed"
|
||||
assert fixed == "x = 1\ny = 2\n"
|
||||
|
||||
|
||||
def test_clean_file_no_warnings():
|
||||
"""A clean file should produce no warnings."""
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
gate = _run_gate_on_file(tmp, "test.py", "x = 1\ny = 2\n")
|
||||
assert gate.warnings == 0
|
||||
assert gate.failures == 0
|
||||
|
||||
|
||||
# -- missing final newline -------------------------------------------------
|
||||
|
||||
def test_missing_final_newline_warns():
|
||||
"""File without trailing newline should warn."""
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
gate = _run_gate_on_file(tmp, "test.py", "x = 1")
|
||||
assert gate.warnings >= 1, "Expected warning for missing final newline"
|
||||
|
||||
|
||||
def test_missing_final_newline_fixed():
|
||||
"""With fix=True, missing final newline should be added."""
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
p = _write_file(tmp, "test.py", "x = 1")
|
||||
gate = QualityGate(fix=True)
|
||||
gate.check_file(p)
|
||||
fixed = p.read_text()
|
||||
assert fixed.endswith("\n"), "Fixed file should end with newline"
|
||||
|
||||
|
||||
# -- function length (JS/TS) -----------------------------------------------
|
||||
|
||||
def test_short_function_passes():
|
||||
"""A short JS function should not warn or fail."""
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
code = "function hello() {\n return 1;\n}\n"
|
||||
gate = _run_gate_on_file(tmp, "test.js", code)
|
||||
assert gate.failures == 0
|
||||
assert gate.warnings == 0
|
||||
|
||||
|
||||
def test_medium_function_warns():
|
||||
"""JS function over 20 lines should warn."""
|
||||
body = "\n".join(f" console.log({i});" for i in range(22))
|
||||
code = f"function big() {{\n{body}\n}}\n"
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
gate = _run_gate_on_file(tmp, "test.js", code)
|
||||
assert gate.warnings >= 1, "Expected warning for function over 20 lines"
|
||||
|
||||
|
||||
def test_long_function_fails():
|
||||
"""JS function over 50 lines should fail."""
|
||||
body = "\n".join(f" console.log({i});" for i in range(52))
|
||||
code = f"function huge() {{\n{body}\n}}\n"
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
gate = _run_gate_on_file(tmp, "test.js", code)
|
||||
assert gate.failures >= 1, "Expected failure for function over 50 lines"
|
||||
|
||||
|
||||
def test_python_function_length_not_checked():
|
||||
"""Python functions should not be checked by the JS regex."""
|
||||
body = "\n".join(f" print({i})" for i in range(60))
|
||||
code = f"def huge():\n{body}\n"
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
gate = _run_gate_on_file(tmp, "test.py", code)
|
||||
assert gate.failures == 0, "Python functions should not trigger JS length check"
|
||||
|
||||
|
||||
# -- file type filtering ---------------------------------------------------
|
||||
|
||||
def test_non_code_file_skipped():
|
||||
"""Non-code files (.md, .json, .txt) should be skipped."""
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
gate = _run_gate_on_file(tmp, "README.md", "# Title \ntrailing ws\n")
|
||||
assert gate.warnings == 0, "Markdown files should be skipped"
|
||||
assert gate.failures == 0
|
||||
|
||||
|
||||
def test_typescript_checked():
|
||||
"""TypeScript files should be checked."""
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
gate = _run_gate_on_file(tmp, "test.ts", "x = 1 \n")
|
||||
assert gate.warnings >= 1, "TypeScript files should be checked"
|
||||
|
||||
|
||||
# -- directory traversal ---------------------------------------------------
|
||||
|
||||
def test_run_scans_directory():
|
||||
"""Gate.run() should scan all files in a directory tree."""
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
_write_file(tmp, "clean.py", "x = 1\n")
|
||||
_write_file(tmp, "dirty.js", "x = 1 \n")
|
||||
_write_file(tmp, "sub/nested.ts", "y = 2 \n")
|
||||
gate = QualityGate()
|
||||
gate.run(tmp)
|
||||
assert gate.warnings >= 2, "Should find trailing whitespace in both dirty files"
|
||||
|
||||
|
||||
def test_run_skips_node_modules():
|
||||
"""Gate.run() should skip node_modules directories."""
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
_write_file(tmp, "clean.py", "x = 1\n")
|
||||
_write_file(tmp, "node_modules/pkg/index.js", "x = 1 \n")
|
||||
gate = QualityGate()
|
||||
gate.run(tmp)
|
||||
assert gate.warnings == 0, "node_modules should be skipped"
|
||||
|
||||
|
||||
def test_run_skips_git_dir():
|
||||
"""Gate.run() should skip .git directories."""
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
_write_file(tmp, "clean.py", "x = 1\n")
|
||||
_write_file(tmp, ".git/hooks/pre-commit", "x = 1 \n")
|
||||
gate = QualityGate()
|
||||
gate.run(tmp)
|
||||
assert gate.warnings == 0, ".git should be skipped"
|
||||
|
||||
|
||||
# -- exit code -------------------------------------------------------------
|
||||
|
||||
def test_failures_cause_exit_code_1():
|
||||
"""Gate with failures should exit with code 1."""
|
||||
import subprocess
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
body = "\n".join(f" console.log({i});" for i in range(52))
|
||||
_write_file(tmp, "huge.js", f"function f() {{\n{body}\n}}\n")
|
||||
r = subprocess.run(
|
||||
[sys.executable, str(Path(__file__).resolve().parent.parent / "scripts" / "ci_automation_gate.py"), tmp],
|
||||
capture_output=True, text=True
|
||||
)
|
||||
assert r.returncode == 1, f"Expected exit 1, got {r.returncode}"
|
||||
|
||||
|
||||
def test_clean_directory_exits_0():
|
||||
"""Gate on clean directory should exit 0."""
|
||||
import subprocess
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
_write_file(tmp, "clean.py", "x = 1\ny = 2\n")
|
||||
r = subprocess.run(
|
||||
[sys.executable, str(Path(__file__).resolve().parent.parent / "scripts" / "ci_automation_gate.py"), tmp],
|
||||
capture_output=True, text=True
|
||||
)
|
||||
assert r.returncode == 0, f"Expected exit 0, got {r.returncode}"
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# TASK GATE TESTS
|
||||
# ===========================================================================
|
||||
|
||||
# Import task_gate functions directly — test the pure logic
|
||||
from task_gate import check_agent_lane, FILTER_TAGS, AGENT_USERNAMES
|
||||
|
||||
|
||||
# -- filter tags -----------------------------------------------------------
|
||||
|
||||
def test_epic_tag_filtered():
|
||||
"""Issues with [EPIC] tag should be filtered."""
|
||||
title = "[EPIC] Build the thing"
|
||||
for tag in FILTER_TAGS:
|
||||
tag_clean = tag.upper().replace("[", "").replace("]", "")
|
||||
if tag_clean in title.upper():
|
||||
return # Found
|
||||
assert False, "EPIC tag should be detected by FILTER_TAGS"
|
||||
|
||||
|
||||
def test_permanent_tag_filtered():
|
||||
"""Issues with [DO NOT CLOSE] tag should be filtered."""
|
||||
title = "[DO NOT CLOSE] Keep this open forever"
|
||||
title_upper = title.upper()
|
||||
matched = any(
|
||||
tag.upper().replace("[", "").replace("]", "") in title_upper
|
||||
for tag in FILTER_TAGS
|
||||
)
|
||||
assert matched, "[DO NOT CLOSE] should be filtered"
|
||||
|
||||
|
||||
def test_normal_title_not_filtered():
|
||||
"""Normal issue titles should not be filtered."""
|
||||
title = "Fix the login bug in auth.py"
|
||||
title_upper = title.upper()
|
||||
matched = any(
|
||||
tag.upper().replace("[", "").replace("]", "") in title_upper
|
||||
for tag in FILTER_TAGS
|
||||
)
|
||||
assert not matched, "Normal title should not be filtered"
|
||||
|
||||
|
||||
def test_morning_report_filtered():
|
||||
"""[MORNING REPORT] issues should be filtered."""
|
||||
title = "[MORNING REPORT] Fleet status 2026-04-13"
|
||||
title_upper = title.upper()
|
||||
matched = any(
|
||||
tag.upper().replace("[", "").replace("]", "") in title_upper
|
||||
for tag in FILTER_TAGS
|
||||
)
|
||||
assert matched, "[MORNING REPORT] should be filtered"
|
||||
|
||||
|
||||
# -- agent lane checker ----------------------------------------------------
|
||||
|
||||
def test_lane_check_no_config():
|
||||
"""With no lane config, lane check should pass."""
|
||||
ok, msg = check_agent_lane("groq", "Fix bug", [], {})
|
||||
assert ok
|
||||
assert "No lane config" in msg
|
||||
|
||||
|
||||
def test_lane_check_agent_not_in_config():
|
||||
"""Agent not in lane config should pass."""
|
||||
lanes = {"ezra": ["docs"]}
|
||||
ok, msg = check_agent_lane("groq", "Fix bug", [], lanes)
|
||||
assert ok
|
||||
assert "No lanes defined" in msg
|
||||
|
||||
|
||||
def test_lane_check_agent_in_config():
|
||||
"""Agent in lane config should return their lanes."""
|
||||
lanes = {"groq": ["code", "infra"]}
|
||||
ok, msg = check_agent_lane("groq", "Fix bug", [], lanes)
|
||||
assert ok
|
||||
assert "groq" in msg
|
||||
assert "code" in msg
|
||||
|
||||
|
||||
# -- agent usernames -------------------------------------------------------
|
||||
|
||||
def test_known_agents_in_usernames():
|
||||
"""Core agent usernames should be registered."""
|
||||
assert "groq" in AGENT_USERNAMES
|
||||
assert "ezra" in AGENT_USERNAMES
|
||||
assert "bezalel" in AGENT_USERNAMES
|
||||
assert "timmy" in AGENT_USERNAMES
|
||||
assert "codex-agent" in AGENT_USERNAMES
|
||||
|
||||
|
||||
# -- pre-task gate (mocked API) -------------------------------------------
|
||||
|
||||
def test_pre_task_gate_issue_not_found():
|
||||
"""Pre-task gate should fail if issue doesn't exist."""
|
||||
from task_gate import pre_task_gate
|
||||
with patch("task_gate.gitea_get", return_value=None):
|
||||
passed, msgs = pre_task_gate("timmy-config", 99999, "groq")
|
||||
assert not passed
|
||||
assert any("not found" in m for m in msgs)
|
||||
|
||||
|
||||
def test_pre_task_gate_filter_tag_blocks():
|
||||
"""Pre-task gate should block filtered issues."""
|
||||
from task_gate import pre_task_gate
|
||||
mock_issue = {
|
||||
"title": "[EPIC] Big thing",
|
||||
"assignees": [],
|
||||
"labels": [],
|
||||
}
|
||||
|
||||
def mock_gitea_get(path):
|
||||
if "issues/100" in path:
|
||||
return mock_issue
|
||||
if "branches" in path:
|
||||
return []
|
||||
if "pulls" in path:
|
||||
return []
|
||||
return None
|
||||
|
||||
with patch("task_gate.gitea_get", side_effect=mock_gitea_get):
|
||||
passed, msgs = pre_task_gate("timmy-config", 100, "groq")
|
||||
assert not passed
|
||||
assert any("filter" in m.lower() for m in msgs)
|
||||
|
||||
|
||||
def test_pre_task_gate_assigned_agent_blocks():
|
||||
"""Pre-task gate should block issues assigned to other agents."""
|
||||
from task_gate import pre_task_gate
|
||||
mock_issue = {
|
||||
"title": "Fix bug",
|
||||
"assignees": [{"login": "ezra"}],
|
||||
"labels": [],
|
||||
}
|
||||
|
||||
def mock_gitea_get(path):
|
||||
if "issues/100" in path:
|
||||
return mock_issue
|
||||
if "branches" in path:
|
||||
return []
|
||||
if "pulls" in path:
|
||||
return []
|
||||
return None
|
||||
|
||||
with patch("task_gate.gitea_get", side_effect=mock_gitea_get):
|
||||
passed, msgs = pre_task_gate("timmy-config", 100, "groq")
|
||||
assert not passed
|
||||
assert any("Already assigned" in m for m in msgs)
|
||||
|
||||
|
||||
def test_pre_task_gate_existing_pr_blocks():
|
||||
"""Pre-task gate should block issues with existing PRs."""
|
||||
from task_gate import pre_task_gate
|
||||
mock_issue = {
|
||||
"title": "Fix bug",
|
||||
"assignees": [],
|
||||
"labels": [],
|
||||
}
|
||||
mock_prs = [{"number": 50, "title": "Fix for #100", "body": "Closes #100"}]
|
||||
|
||||
def mock_gitea_get(path):
|
||||
if "issues/100" in path:
|
||||
return mock_issue
|
||||
if "branches" in path:
|
||||
return []
|
||||
if "pulls" in path:
|
||||
return mock_prs
|
||||
return None
|
||||
|
||||
with patch("task_gate.gitea_get", side_effect=mock_gitea_get):
|
||||
passed, msgs = pre_task_gate("timmy-config", 100, "groq")
|
||||
assert not passed
|
||||
assert any("Open PR" in m for m in msgs)
|
||||
|
||||
|
||||
def test_pre_task_gate_clean_passes():
|
||||
"""Pre-task gate should pass for clean issues."""
|
||||
from task_gate import pre_task_gate
|
||||
|
||||
def mock_gitea_get(path):
|
||||
if "issues/100" in path:
|
||||
return {"title": "Fix bug", "assignees": [], "labels": []}
|
||||
if "branches" in path:
|
||||
return []
|
||||
if "pulls" in path:
|
||||
return []
|
||||
return None
|
||||
|
||||
with patch("task_gate.gitea_get", side_effect=mock_gitea_get):
|
||||
passed, msgs = pre_task_gate("timmy-config", 100, "groq")
|
||||
assert passed
|
||||
|
||||
|
||||
# -- post-task gate (mocked API) ------------------------------------------
|
||||
|
||||
def test_post_task_gate_missing_branch():
|
||||
"""Post-task gate should fail if branch doesn't exist."""
|
||||
from task_gate import post_task_gate
|
||||
with patch("task_gate.gitea_get", return_value=None):
|
||||
passed, msgs = post_task_gate("timmy-config", 100, "groq", "groq/fix-100")
|
||||
assert not passed
|
||||
assert any("does not exist" in m for m in msgs)
|
||||
|
||||
|
||||
def test_post_task_gate_no_agent_prefix_warns():
|
||||
"""Post-task gate should warn if branch doesn't start with agent name."""
|
||||
from task_gate import post_task_gate
|
||||
|
||||
def mock_gitea_get(path):
|
||||
if "branches/fix-100" in path:
|
||||
return {"name": "fix-100"}
|
||||
if "compare" in path:
|
||||
return {"commits": [{"id": "abc"}], "diff_files": ["file.py"]}
|
||||
if "pulls" in path:
|
||||
return []
|
||||
return None
|
||||
|
||||
with patch("task_gate.gitea_get", side_effect=mock_gitea_get):
|
||||
passed, msgs = post_task_gate("timmy-config", 100, "groq", "fix-100")
|
||||
assert passed # Warning, not failure
|
||||
assert any("doesn't start with agent" in m or "convention" in m for m in msgs)
|
||||
|
||||
|
||||
def test_post_task_gate_no_commits_fails():
|
||||
"""Post-task gate should fail if branch has no commits ahead of main."""
|
||||
from task_gate import post_task_gate
|
||||
|
||||
def mock_gitea_get(path):
|
||||
if "branches/" in path:
|
||||
return {"name": "groq/fix-100"}
|
||||
if "compare" in path:
|
||||
return {"commits": [], "diff_files": []}
|
||||
if "pulls" in path:
|
||||
return []
|
||||
return None
|
||||
|
||||
with patch("task_gate.gitea_get", side_effect=mock_gitea_get):
|
||||
passed, msgs = post_task_gate("timmy-config", 100, "groq", "groq/fix-100")
|
||||
assert not passed
|
||||
assert any("no commits" in m.lower() for m in msgs)
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# INTEGRATION: gate on real script files
|
||||
# ===========================================================================
|
||||
|
||||
def test_ci_gate_on_actual_task_gate():
|
||||
"""Run QualityGate on task_gate.py itself — should pass."""
|
||||
gate_path = Path(__file__).resolve().parent.parent / "scripts" / "task_gate.py"
|
||||
if gate_path.exists():
|
||||
gate = QualityGate()
|
||||
gate.check_file(gate_path)
|
||||
assert gate.failures == 0, f"task_gate.py should pass quality gate, got {gate.failures} failures"
|
||||
|
||||
|
||||
def test_ci_gate_on_actual_ci_automation_gate():
|
||||
"""Run QualityGate on ci_automation_gate.py itself — should pass."""
|
||||
gate_path = Path(__file__).resolve().parent.parent / "scripts" / "ci_automation_gate.py"
|
||||
if gate_path.exists():
|
||||
gate = QualityGate()
|
||||
gate.check_file(gate_path)
|
||||
assert gate.failures == 0, f"ci_automation_gate.py should pass quality gate, got {gate.failures} failures"
|
||||
Reference in New Issue
Block a user