Files
ledgrab/server/tests/api/routes/test_webhooks_routes.py
T
alexei.dolgolyov 888f8fd16e refactor(types): PEP-604 union sweep + UP007/UP045 enforcement
ruff --select UP007,UP045 --fix converted ~1760 sites across the
backend: `Optional[T]` → `T | None`, `Union[X, Y]` → `X | Y`. The
remaining module-level alias targets that ruff conservatively skips
(BindableFloatInput, ColorList, DeviceConfig) were converted by hand
earlier in the pass. black -formatted the result so the wider unions
fit cleanly under the 100-char line budget.

pyproject.toml now sets [tool.ruff.lint] extend-select = ["UP007",
"UP045"] so future legacy imports fire CI on every push. The
pre-commit ruff hook was bumped from v0.8.0 -> v0.15.12 to recognise
UP045 (split off from UP007 in v0.13).
2026-05-23 01:21:44 +03:00

67 lines
2.2 KiB
Python

"""Tests for webhook routes — trigger, validation, rate limiting."""
import time
import pytest
from ledgrab.api.routes.webhooks import _check_rate_limit, _rate_hits
# ---------------------------------------------------------------------------
# Rate limiter unit tests (pure function, no HTTP)
# ---------------------------------------------------------------------------
class TestRateLimiter:
def setup_method(self):
"""Clear rate-limit state between tests."""
_rate_hits.clear()
def test_allows_under_limit(self):
for _ in range(29):
_check_rate_limit("1.2.3.4") # should not raise
def test_rejects_at_limit(self):
for _ in range(30):
_check_rate_limit("1.2.3.4")
from fastapi import HTTPException
with pytest.raises(HTTPException) as exc_info:
_check_rate_limit("1.2.3.4")
assert exc_info.value.status_code == 429
def test_separate_ips_independent(self):
for _ in range(30):
_check_rate_limit("10.0.0.1")
# Different IP should still be allowed
_check_rate_limit("10.0.0.2") # should not raise
def test_window_expiry(self):
"""Timestamps outside the 60s window are pruned."""
old_time = time.time() - 120 # 2 minutes ago
_rate_hits["1.2.3.4"] = [old_time] * 30
# Old entries should be pruned, allowing new requests
_check_rate_limit("1.2.3.4") # should not raise
# ---------------------------------------------------------------------------
# Webhook payload validation
# ---------------------------------------------------------------------------
class TestWebhookPayload:
def test_valid_payload_model(self):
from ledgrab.api.routes.webhooks import WebhookPayload
p = WebhookPayload(action="activate")
assert p.action == "activate"
p2 = WebhookPayload(action="deactivate")
assert p2.action == "deactivate"
def test_arbitrary_action_accepted_by_model(self):
"""The model accepts any string; validation is in the route handler."""
from ledgrab.api.routes.webhooks import WebhookPayload
p = WebhookPayload(action="bogus")
assert p.action == "bogus"