Name each project's notifier in its config, with Mattermost and Slack as backends
CI / tests (pull_request) Successful in 2m3s

This commit is contained in:
2026-11-14 22:53:00 +01:00
parent f648f4235a
commit 6a553b9574
25 changed files with 495 additions and 229 deletions
View File
+51
View File
@@ -0,0 +1,51 @@
"""Sends a direct message from a Slack app's bot to one user, through Slack's Web API. `notifier` picks it where a project's config names `slack`."""
import dataclasses
import pathlib
from failure import Failure
from rest_client.json_request import Http
from rest_client import json_request
from rest_client.env_file import read_env
KEYS = ("SLACK_TOKEN", "SLACK_RECIPIENT")
# Slack's one host for every workspace.
API = "https://slack.com/api"
# Seconds each connect and each read may wait, so an unreachable server holds loop-claude's interrupt only briefly.
TIMEOUT = 10
@dataclasses.dataclass(frozen=True)
class Config:
token: str
recipient: str
def read_config(path: pathlib.Path) -> Config | Failure:
"""The bot token and recipient that path's KEY=value lines hold."""
values = read_env(path, KEYS, "the bot's token")
if isinstance(values, Failure):
return values
return Config(*(values[key] for key in KEYS))
def send(config: Config, message: str, http: Http) -> Failure | None:
"""Posts message to the recipient's member ID, which Slack opens as a DM from the app's bot; the bot needs the `chat:write` scope."""
answer = http("POST", f"{API}/chat.postMessage", config.token, {"channel": config.recipient, "text": message})
if isinstance(answer, Failure):
return answer
if isinstance(answer, dict) and answer.get("ok") is True:
return None
# Slack answers 200 with `ok` false and a short code, such as `channel_not_found` or `invalid_auth`.
error = answer.get("error") if isinstance(answer, dict) else None
return Failure(f"POST /api/chat.postMessage refused the message: {error if isinstance(error, str) and error else 'no error code'}")
def http_json(method: str, url: str, token: str, body: object) -> object:
"""The JSON that url answers to the bot's request, or a Failure saying why there is none."""
return json_request.http_json(method, url, f"Bearer {token}", body, TIMEOUT, error_message)
def error_message(answer: object) -> str:
"""Slack's error code in the JSON of an error answer; empty where it holds none."""
error = answer.get("error") if isinstance(answer, dict) else None
return error if isinstance(error, str) else ""
+78
View File
@@ -0,0 +1,78 @@
import pathlib
import sys
import tempfile
import unittest
import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from slack_dm import dm
from failure import Failure
CONFIG = dm.Config("xoxb-secret", "U0123ABCD")
class Slack:
"""Slack's answer to every request, recording each one it gets."""
def __init__(self, answer: object) -> None:
self.answer = answer
self.requests: list[tuple[str, str, str, object]] = []
def __call__(self, method: str, url: str, token: str, body: object) -> object:
self.requests.append((method, url, token, body))
return self.answer
def env_file(folder: str, text: str, mode: int = 0o600) -> pathlib.Path:
path = pathlib.Path(folder) / "slack.env"
path.write_text(text)
path.chmod(mode)
return path
class ReadConfig(unittest.TestCase):
def test_reads_the_token_and_the_recipient_skipping_comments_and_quotes(self):
with tempfile.TemporaryDirectory() as folder:
path = env_file(folder, '# acme\nSLACK_TOKEN="xoxb-secret"\nSLACK_RECIPIENT = U0123ABCD\nOTHER=1\n')
self.assertEqual(dm.read_config(path), CONFIG)
def test_names_each_key_missing_and_refuses_a_file_others_can_read(self):
with tempfile.TemporaryDirectory() as folder:
path = env_file(folder, "SLACK_TOKEN=xoxb-secret\n")
self.assertEqual(dm.read_config(path), Failure(f"{path} lacks SLACK_RECIPIENT"))
path = env_file(folder, "SLACK_TOKEN=t\nSLACK_RECIPIENT=r\n", 0o640)
self.assertEqual(dm.read_config(path), Failure(f"{path} holds the bot's token, so only its owner may read it; run chmod 600 {path}"))
class Send(unittest.TestCase):
def test_posts_the_message_to_the_recipients_member_id_with_the_token(self):
slack = Slack({"ok": True, "ts": "1.2"})
self.assertIsNone(dm.send(CONFIG, "Which one?", slack))
self.assertEqual(slack.requests, [("POST", "https://slack.com/api/chat.postMessage", "xoxb-secret", {"channel": "U0123ABCD", "text": "Which one?"})])
def test_fails_naming_slacks_error_code_where_slack_answers_ok_false(self):
self.assertEqual(dm.send(CONFIG, "hi", Slack({"ok": False, "error": "invalid_auth"})), Failure("POST /api/chat.postMessage refused the message: invalid_auth"))
def test_fails_on_an_answer_that_says_neither_ok_nor_an_error(self):
for answer in ({}, ["ok"], {"ok": "true"}, {"ok": False, "error": 7}):
with self.subTest(answer=answer):
self.assertEqual(dm.send(CONFIG, "hi", Slack(answer)), Failure("POST /api/chat.postMessage refused the message: no error code"))
def test_passes_on_the_failure_of_the_request_itself(self):
failed = Failure("cannot reach https://slack.com: timed out")
self.assertEqual(dm.send(CONFIG, "hi", Slack(failed)), failed)
class HttpJson(unittest.TestCase):
def test_sends_the_token_as_a_bearer_and_reads_slacks_code_from_an_error(self):
with unittest.mock.patch.object(dm.json_request, "http_json", return_value={"ok": True}) as sent:
self.assertEqual(dm.http_json("POST", "https://slack.com/api/chat.postMessage", "xoxb-secret", {"text": "hi"}), {"ok": True})
sent.assert_called_once_with("POST", "https://slack.com/api/chat.postMessage", "Bearer xoxb-secret", {"text": "hi"}, dm.TIMEOUT, dm.error_message)
for answer, code in (({"error": "ratelimited"}, "ratelimited"), ({"error": 7}, ""), ({}, ""), (["error"], "")):
with self.subTest(answer=answer):
self.assertEqual(dm.error_message(answer), code)
if __name__ == "__main__":
unittest.main()