Files
gitea-codex/tests/test_webhook.py
Space-Banane 860ccb731d First MVP
2026-05-22 19:25:57 +02:00

82 lines
2.4 KiB
Python

from __future__ import annotations
import hashlib
import hmac
import json
from typing import Any
from fastapi.testclient import TestClient
from gitea_codex_bot.main import app
def _sign(payload: bytes) -> str:
return hmac.new(b"secret", payload, hashlib.sha256).hexdigest()
def _payload(comment_body: str, *, username: str = "alice", comment_id: int = 11) -> dict[str, Any]:
return {
"repository": {"full_name": "acme/repo"},
"sender": {"username": username},
"comment": {"id": comment_id, "body": comment_body},
"issue": {"number": 9, "pull_request": {"url": "x"}},
"pull_request": {"head": {"sha": "abcdef123"}},
}
def test_webhook_rejects_bad_signature() -> None:
client = TestClient(app)
payload = b"{}"
response = client.post(
"/webhook/gitea",
content=payload,
headers={"X-Gitea-Event": "issue_comment", "X-Gitea-Signature": "bad"},
)
assert response.status_code == 401
def test_webhook_ignores_bot_comment(monkeypatch) -> None:
client = TestClient(app)
payload = _payload("@codex review", username="codex-bot")
raw = json.dumps(payload).encode()
response = client.post(
"/webhook/gitea",
content=raw,
headers={
"X-Gitea-Event": "issue_comment",
"X-Gitea-Delivery": "d-1",
"X-Gitea-Signature": _sign(raw),
"Content-Type": "application/json",
},
)
assert response.status_code == 200
assert response.json()["reason"] == "bot comment ignored"
def test_webhook_accepts_review_and_queues(monkeypatch) -> None:
posted_comments: list[str] = []
def _post_issue_comment(self, repo: str, pr_number: int, body: str) -> int:
posted_comments.append(body)
return 100
monkeypatch.setattr("gitea_codex_bot.services.gitea.GiteaClient.post_issue_comment", _post_issue_comment)
client = TestClient(app)
payload_obj = _payload("@codex review security", username="alice", comment_id=111)
raw = json.dumps(payload_obj).encode()
response = client.post(
"/webhook/gitea",
content=raw,
headers={
"X-Gitea-Event": "issue_comment",
"X-Gitea-Delivery": "d-2",
"X-Gitea-Signature": _sign(raw),
"Content-Type": "application/json",
},
)
assert response.status_code == 200
assert response.json()["status"] == "queued"
assert posted_comments