From 3a53532e58a2b63f11cfd55f160ed5a30bd786ab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jegors=20=C4=8Cemisovs?= Date: Thu, 5 Nov 2026 19:01:13 +0200 Subject: [PATCH 1/2] refactor: resolve SonarCloud complexity and style issues --- .sonarcloud.properties | 8 ++++ bot.py | 6 ++- dicechess/client.py | 70 +++++++++++++++++++-------------- tests/test_client.py | 89 ++++++++++++++++++++++++++++++++++++++++++ webhook.py | 2 +- 5 files changed, 144 insertions(+), 31 deletions(-) create mode 100644 .sonarcloud.properties create mode 100644 tests/test_client.py diff --git a/.sonarcloud.properties b/.sonarcloud.properties new file mode 100644 index 0000000..bdc437b --- /dev/null +++ b/.sonarcloud.properties @@ -0,0 +1,8 @@ +# ============================================================================== +# SonarCloud Automatic Analysis Configuration +# ============================================================================== + +sonar.sources=dicechess,bot.py,webhook.py,register.py +sonar.tests=tests +sonar.test.inclusions=tests/**/test_*.py +sonar.sourceEncoding=UTF-8 diff --git a/bot.py b/bot.py index d6061f9..92a2b59 100755 --- a/bot.py +++ b/bot.py @@ -28,6 +28,10 @@ from dicechess import BotClient, DEFAULT_BASE_URL +# Move choice is not security-sensitive; the OS-backed generator keeps static analysis quiet and +# needs no seeding. +_RNG = random.SystemRandom() + logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") log = logging.getLogger("bot") @@ -45,7 +49,7 @@ def choose_move(legal_moves: dict) -> list[str]: path: list[str] = [] node = legal_moves while node: - move = random.choice(list(node.keys())) + move = _RNG.choice(list(node.keys())) path.append(move) node = node[move] return path diff --git a/dicechess/client.py b/dicechess/client.py index ea34190..0e1b52e 100644 --- a/dicechess/client.py +++ b/dicechess/client.py @@ -116,47 +116,59 @@ def register_webhook(self, url: str) -> dict: # ── transport ────────────────────────────────────────────────────────────── + def _build_request(self, method: str, url: str, payload: bytes | None, auth: bool) -> urllib.request.Request: + req = urllib.request.Request(url, data=payload, method=method) + req.add_header("User-Agent", USER_AGENT) + if payload is not None: + req.add_header("Content-Type", "application/json") + if auth and self.token: + req.add_header("Authorization", f"Bearer {self.token}") + return req + + def _retry_delay(self, error: urllib.error.HTTPError, attempt: int) -> float | None: + """Seconds to wait before retrying a failed HTTP response, or ``None`` when it is final. + + A ``401`` refreshes the token first and retries immediately (delay ``0``). + """ + status = error.code + if attempt > self.max_retries: + return None + if status == 401 and self._on_unauthorized: + log.warning("401 Unauthorized — refreshing token") + self._on_unauthorized(self) + return 0.0 + if status == 429: + delay = float(error.headers.get("Retry-After", self._backoff(attempt))) + log.warning("429 Too Many Requests — retrying in %.1fs", delay) + return delay + if 500 <= status < 600: + delay = self._backoff(attempt) + log.warning("HTTP %d — retrying in %.1fs", status, delay) + return delay + return None + def _request(self, method: str, path: str, body: Any = None, auth: bool = True) -> dict: url = f"{self.base_url}{path}" payload = json.dumps(body).encode() if body is not None else None attempt = 0 while True: attempt += 1 - req = urllib.request.Request(url, data=payload, method=method) - req.add_header("User-Agent", USER_AGENT) - if payload is not None: - req.add_header("Content-Type", "application/json") - if auth and self.token: - req.add_header("Authorization", f"Bearer {self.token}") + req = self._build_request(method, url, payload, auth) try: with urllib.request.urlopen(req, timeout=30) as resp: text = resp.read().decode() return json.loads(text) if text else {} except urllib.error.HTTPError as e: - status = e.code - detail = e.read().decode(errors="replace") - if status == 401 and self._on_unauthorized and attempt <= self.max_retries: - log.warning("401 Unauthorized — refreshing token") - self._on_unauthorized(self) - continue - if status == 429 and attempt <= self.max_retries: - delay = float(e.headers.get("Retry-After", self._backoff(attempt))) - log.warning("429 Too Many Requests — retrying in %.1fs", delay) - time.sleep(delay) - continue - if 500 <= status < 600 and attempt <= self.max_retries: - delay = self._backoff(attempt) - log.warning("HTTP %d — retrying in %.1fs", status, delay) - time.sleep(delay) - continue - raise ApiError(status, detail) from e + delay = self._retry_delay(e, attempt) + if delay is None: + raise ApiError(e.code, e.read().decode(errors="replace")) from e + time.sleep(delay) except urllib.error.URLError as e: - if attempt <= self.max_retries: - delay = self._backoff(attempt) - log.warning("network error %s — retrying in %.1fs", e.reason, delay) - time.sleep(delay) - continue - raise + if attempt > self.max_retries: + raise + delay = self._backoff(attempt) + log.warning("network error %s — retrying in %.1fs", e.reason, delay) + time.sleep(delay) @staticmethod def _backoff(attempt: int) -> float: diff --git a/tests/test_client.py b/tests/test_client.py new file mode 100644 index 0000000..7718413 --- /dev/null +++ b/tests/test_client.py @@ -0,0 +1,89 @@ +"""Hermetic tests for ``BotClient`` retry handling — urllib is stubbed, nothing touches the network.""" + +import io +import json +import unittest +import urllib.error +from unittest import mock + +from dicechess import ApiError, BotClient + + +def _http_error(status: int, headers: dict | None = None) -> urllib.error.HTTPError: + return urllib.error.HTTPError("http://x/y", status, "err", headers or {}, io.BytesIO(b"detail")) + + +class _Response: + def __init__(self, payload: dict): + self._data = json.dumps(payload).encode() + + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + def read(self) -> bytes: + return self._data + + +class RequestRetryTests(unittest.TestCase): + def _call(self, outcomes, **client_kwargs): + client = BotClient(base_url="http://x", token="t", **client_kwargs) + with ( + mock.patch("urllib.request.urlopen", side_effect=outcomes) as urlopen, + mock.patch("time.sleep") as sleep, + ): + try: + result = client._request("GET", "/p") + except Exception as e: # noqa: BLE001 - the tests assert on the exception type + result = e + return result, urlopen.call_count, [c.args[0] for c in sleep.call_args_list] + + def test_success_needs_one_call(self): + result, calls, sleeps = self._call([_Response({"ok": True})]) + self.assertEqual(result, {"ok": True}) + self.assertEqual((calls, sleeps), (1, [])) + + def test_server_error_backs_off_exponentially_then_succeeds(self): + result, calls, sleeps = self._call([_http_error(503), _http_error(500), _Response({"ok": 1})]) + self.assertEqual(result, {"ok": 1}) + self.assertEqual((calls, sleeps), (3, [1.0, 2.0])) + + def test_rate_limit_honours_retry_after(self): + result, _calls, sleeps = self._call([_http_error(429, {"Retry-After": "7"}), _Response({"ok": 1})]) + self.assertEqual(result, {"ok": 1}) + self.assertEqual(sleeps, [7.0]) + + def test_unauthorized_refreshes_token_and_retries_without_waiting(self): + refreshed = [] + result, calls, sleeps = self._call( + [_http_error(401), _Response({"ok": 1})], on_unauthorized=lambda c: refreshed.append(c) + ) + self.assertEqual(result, {"ok": 1}) + self.assertEqual((len(refreshed), calls, sleeps), (1, 2, [0.0])) + + def test_unauthorized_without_hook_is_final(self): + result, calls, _ = self._call([_http_error(401)]) + self.assertIsInstance(result, ApiError) + self.assertEqual((result.status, calls), (401, 1)) + + def test_client_error_is_not_retried(self): + result, calls, _ = self._call([_http_error(404)]) + self.assertIsInstance(result, ApiError) + self.assertEqual((result.status, result.body, calls), (404, "detail", 1)) + + def test_retries_are_bounded(self): + result, calls, _ = self._call([_http_error(503)] * 10, max_retries=2) + self.assertIsInstance(result, ApiError) + self.assertEqual(calls, 3) + + def test_network_error_is_retried_then_raised(self): + err = urllib.error.URLError("down") + result, calls, sleeps = self._call([err, err, err], max_retries=2) + self.assertIsInstance(result, urllib.error.URLError) + self.assertEqual((calls, sleeps), (3, [1.0, 2.0])) + + +if __name__ == "__main__": + unittest.main() diff --git a/webhook.py b/webhook.py index 7d40736..6d94deb 100755 --- a/webhook.py +++ b/webhook.py @@ -64,7 +64,7 @@ def main() -> None: if not SECRET: raise SystemExit("set DICECHESS_WEBHOOK_SECRET (printed by register.py) before starting") log.info("webhook handler listening on :%d", PORT) - ThreadingHTTPServer(("", PORT), Handler).serve_forever() + ThreadingHTTPServer(("", PORT), Handler).serve_forever() # NOSONAR: local runner runs behind a TLS reverse proxy or tunnel if __name__ == "__main__": From cbbca41ec2c2651278fef713b8399144ba3d060b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jegors=20=C4=8Cemisovs?= Date: Thu, 5 Nov 2026 19:06:03 +0200 Subject: [PATCH 2/2] style: use noqa syntax for S5332 suppression --- webhook.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/webhook.py b/webhook.py index 6d94deb..0093bdb 100755 --- a/webhook.py +++ b/webhook.py @@ -64,7 +64,8 @@ def main() -> None: if not SECRET: raise SystemExit("set DICECHESS_WEBHOOK_SECRET (printed by register.py) before starting") log.info("webhook handler listening on :%d", PORT) - ThreadingHTTPServer(("", PORT), Handler).serve_forever() # NOSONAR: local runner runs behind a TLS reverse proxy or tunnel + # Local runner intended to run behind a TLS reverse proxy or tunnel. + ThreadingHTTPServer(("", PORT), Handler).serve_forever() # noqa: S5332 if __name__ == "__main__":