269 lines
13 KiB
Python
269 lines
13 KiB
Python
import http.server
|
|
import io
|
|
import json
|
|
import pathlib
|
|
import socket
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import threading
|
|
import unittest
|
|
import unittest.mock
|
|
|
|
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
|
|
|
from mattermost_dm import dm, main
|
|
from failure import Failure
|
|
from test_env import isolated_env
|
|
|
|
TOOL = pathlib.Path(__file__).resolve().parents[1] / "mattermost-dm"
|
|
CONFIG = dm.Config("https://chat.example", "secret-token", "lilleman")
|
|
|
|
|
|
def env_file(folder: str, text: str, mode: int = 0o600) -> pathlib.Path:
|
|
path = pathlib.Path(folder) / ".env"
|
|
path.write_text(text)
|
|
path.chmod(mode)
|
|
return path
|
|
|
|
|
|
class FakeServer:
|
|
"""Mattermost's answers by method and path, recording each request it gets."""
|
|
|
|
def __init__(self, answers: dict[tuple[str, str], object]) -> None:
|
|
self.answers = answers
|
|
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.answers[(method, url.removeprefix("https://chat.example"))]
|
|
|
|
|
|
def mattermost() -> FakeServer:
|
|
return FakeServer({
|
|
("GET", "/api/v4/users/me"): {"id": "bot-id"},
|
|
("GET", "/api/v4/users/username/lilleman"): {"id": "human-id"},
|
|
("POST", "/api/v4/channels/direct"): {"id": "channel-id"},
|
|
("POST", "/api/v4/posts"): {"id": "post-id"},
|
|
})
|
|
|
|
|
|
class ReadConfig(unittest.TestCase):
|
|
def test_reads_the_server_the_token_and_the_recipient_skipping_blanks_comments_and_quotes(self):
|
|
with tempfile.TemporaryDirectory() as folder:
|
|
path = env_file(folder, '# larvit-bot\n\nMATTERMOST_URL = https://chat.example/\nMATTERMOST_TOKEN="secret-token"\nMATTERMOST_RECIPIENT=\'lilleman\'\nOTHER=1\n')
|
|
self.assertEqual(dm.read_config(path), dm.Config("https://chat.example", "secret-token", "lilleman"))
|
|
|
|
def test_names_the_file_and_the_keys_it_needs_where_the_file_is_missing(self):
|
|
with tempfile.TemporaryDirectory() as folder:
|
|
path = pathlib.Path(folder) / ".env"
|
|
self.assertEqual(dm.read_config(path), Failure(f"{path} does not exist; it needs MATTERMOST_URL, MATTERMOST_TOKEN and MATTERMOST_RECIPIENT"))
|
|
|
|
def test_names_each_key_missing_or_empty(self):
|
|
with tempfile.TemporaryDirectory() as folder:
|
|
path = env_file(folder, "MATTERMOST_URL=https://chat.example\nMATTERMOST_TOKEN=\n")
|
|
self.assertEqual(dm.read_config(path), Failure(f"{path} lacks MATTERMOST_TOKEN and MATTERMOST_RECIPIENT"))
|
|
|
|
def test_refuses_a_file_that_group_or_others_can_read_since_it_holds_the_token(self):
|
|
with tempfile.TemporaryDirectory() as folder:
|
|
for mode in (0o640, 0o604):
|
|
with self.subTest(mode=oct(mode)):
|
|
path = env_file(folder, "MATTERMOST_URL=https://chat.example\nMATTERMOST_TOKEN=t\nMATTERMOST_RECIPIENT=r\n", mode)
|
|
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}"))
|
|
|
|
def test_refuses_a_server_off_https_which_would_send_the_token_in_the_clear(self):
|
|
with tempfile.TemporaryDirectory() as folder:
|
|
path = env_file(folder, "MATTERMOST_URL=http://chat.example\nMATTERMOST_TOKEN=t\nMATTERMOST_RECIPIENT=r\n")
|
|
self.assertEqual(dm.read_config(path), Failure(f"{path} → MATTERMOST_URL must start with https://, so the token is never sent in the clear"))
|
|
|
|
|
|
class Send(unittest.TestCase):
|
|
def test_finds_both_users_opens_their_direct_channel_and_posts_the_message_there(self):
|
|
server = mattermost()
|
|
self.assertIsNone(dm.send(CONFIG, "Which one?", server))
|
|
self.assertEqual(server.requests, [
|
|
("GET", "https://chat.example/api/v4/users/me", "secret-token", None),
|
|
("GET", "https://chat.example/api/v4/users/username/lilleman", "secret-token", None),
|
|
("POST", "https://chat.example/api/v4/channels/direct", "secret-token", ["bot-id", "human-id"]),
|
|
("POST", "https://chat.example/api/v4/posts", "secret-token", {"channel_id": "channel-id", "message": "Which one?"}),
|
|
])
|
|
|
|
def test_stops_at_the_first_failed_request(self):
|
|
server = mattermost()
|
|
server.answers[("GET", "/api/v4/users/username/lilleman")] = Failure("GET /api/v4/users/username/lilleman answered 404: Unable to find an existing account matching your username.")
|
|
self.assertEqual(dm.send(CONFIG, "Which one?", server), Failure("GET /api/v4/users/username/lilleman answered 404: Unable to find an existing account matching your username."))
|
|
self.assertEqual(len(server.requests), 2)
|
|
|
|
def test_fails_on_an_answer_without_an_id_or_one_that_is_not_an_object(self):
|
|
for answer in ({"status": "OK"}, ["channel-id"], {"id": ""}):
|
|
with self.subTest(answer=answer):
|
|
server = mattermost()
|
|
server.answers[("POST", "/api/v4/channels/direct")] = answer
|
|
self.assertEqual(dm.send(CONFIG, "Which one?", server), Failure("POST /api/v4/channels/direct answered without an id"))
|
|
self.assertEqual(len(server.requests), 3)
|
|
|
|
def test_fails_where_the_post_itself_fails(self):
|
|
server = mattermost()
|
|
server.answers[("POST", "/api/v4/posts")] = Failure("POST /api/v4/posts answered 403: You do not have the appropriate permissions.")
|
|
self.assertEqual(dm.send(CONFIG, "Which one?", server), Failure("POST /api/v4/posts answered 403: You do not have the appropriate permissions."))
|
|
|
|
|
|
class Recorded(http.server.BaseHTTPRequestHandler):
|
|
"""Answers each request with the server's next scripted status and body, recording what it got."""
|
|
|
|
def do_GET(self) -> None:
|
|
self.answer()
|
|
|
|
def do_POST(self) -> None:
|
|
self.answer()
|
|
|
|
def answer(self) -> None:
|
|
length = int(self.headers.get("Content-Length") or 0)
|
|
self.server.got.append((self.command, self.path, dict(self.headers), self.rfile.read(length))) # type: ignore[attr-defined]
|
|
status, body = self.server.script.pop(0) # type: ignore[attr-defined]
|
|
if status is None:
|
|
# Raw bytes, as a server that breaks HTTP sends them.
|
|
self.wfile.write(body)
|
|
self.close_connection = True
|
|
return
|
|
self.send_response(status)
|
|
if 300 <= status < 400:
|
|
self.send_header("Location", "/elsewhere")
|
|
self.send_header("Content-Type", "application/json")
|
|
self.end_headers()
|
|
self.wfile.write(body)
|
|
|
|
def log_message(self, format: str, *args: object) -> None:
|
|
pass
|
|
|
|
|
|
class HttpJson(unittest.TestCase):
|
|
def serve(self, *script: tuple[int, bytes]) -> str:
|
|
server = http.server.HTTPServer(("127.0.0.1", 0), Recorded)
|
|
server.script = list(script) # type: ignore[attr-defined]
|
|
server.got = [] # type: ignore[attr-defined]
|
|
threading.Thread(target=server.serve_forever, daemon=True).start()
|
|
self.addCleanup(server.server_close)
|
|
self.addCleanup(server.shutdown)
|
|
self.server = server
|
|
return f"http://127.0.0.1:{server.server_port}"
|
|
|
|
def test_sends_the_token_as_a_bearer_and_the_body_as_json_and_reads_the_json_answer(self):
|
|
base = self.serve((201, b'{"id": "post-id"}'))
|
|
self.assertEqual(dm.http_json("POST", f"{base}/api/v4/posts", "secret-token", {"message": "hi"}), {"id": "post-id"})
|
|
[(method, path, headers, body)] = self.server.got # type: ignore[attr-defined]
|
|
self.assertEqual((method, path, headers["Authorization"], headers["Content-Type"], json.loads(body)), ("POST", "/api/v4/posts", "Bearer secret-token", "application/json", {"message": "hi"}))
|
|
|
|
def test_names_the_request_the_status_and_mattermosts_message_on_an_error(self):
|
|
base = self.serve((401, b'{"message": "Invalid or expired session, please login again."}'))
|
|
self.assertEqual(dm.http_json("GET", f"{base}/api/v4/users/me", "bad", None), Failure("GET /api/v4/users/me answered 401: Invalid or expired session, please login again."))
|
|
|
|
def test_follows_no_redirect_so_the_token_goes_only_to_the_server_named(self):
|
|
base = self.serve((302, b"{}"))
|
|
self.assertEqual(dm.http_json("GET", f"{base}/api/v4/users/me", "t", None), Failure("GET /api/v4/users/me answered 302: Found"))
|
|
self.assertEqual(len(self.server.got), 1) # type: ignore[attr-defined]
|
|
|
|
def test_sends_no_body_with_a_get(self):
|
|
base = self.serve((200, b'{"id": "bot-id"}'))
|
|
dm.http_json("GET", f"{base}/api/v4/users/me", "t", None)
|
|
[(_, _, headers, body)] = self.server.got # type: ignore[attr-defined]
|
|
self.assertEqual((headers.get("Content-Length"), body), (None, b""))
|
|
|
|
def test_fails_on_an_answer_that_breaks_http(self):
|
|
for raw in (b"garbage\r\n\r\n", b"HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\n{}"):
|
|
with self.subTest(raw=raw):
|
|
base = self.serve((None, raw))
|
|
failed = dm.http_json("GET", f"{base}/api/v4/users/me", "t", None)
|
|
self.assertTrue(isinstance(failed, Failure) and failed.reason.startswith("GET /api/v4/users/me got a broken answer: "), failed)
|
|
|
|
def test_names_the_status_of_an_error_whose_body_is_cut_short(self):
|
|
base = self.serve((None, b"HTTP/1.1 500 Internal Server Error\r\nContent-Length: 100\r\n\r\n{}"))
|
|
self.assertEqual(dm.http_json("GET", f"{base}/api/v4/users/me", "t", None), Failure("GET /api/v4/users/me answered 500: Internal Server Error"))
|
|
|
|
def test_gives_up_on_a_server_that_never_answers_after_the_timeout(self):
|
|
silent = socket.socket()
|
|
self.addCleanup(silent.close)
|
|
silent.bind(("127.0.0.1", 0))
|
|
silent.listen(1)
|
|
base = f"http://127.0.0.1:{silent.getsockname()[1]}"
|
|
with unittest.mock.patch.object(dm, "TIMEOUT", 0.2):
|
|
self.assertEqual(dm.http_json("GET", f"{base}/api/v4/users/me", "t", None), Failure(f"cannot reach {base}: timed out"))
|
|
|
|
def test_fails_on_an_answer_that_is_not_json(self):
|
|
base = self.serve((200, b"<html>"))
|
|
self.assertEqual(dm.http_json("GET", f"{base}/api/v4/users/me", "t", None), Failure("GET /api/v4/users/me answered with something other than JSON"))
|
|
|
|
def test_fails_naming_the_server_it_cannot_reach(self):
|
|
base = self.serve()
|
|
self.server.server_close()
|
|
failed = dm.http_json("GET", f"{base}/api/v4/users/me", "t", None)
|
|
self.assertIsInstance(failed, Failure)
|
|
self.assertTrue(str(getattr(failed, "reason", "")).startswith(f"cannot reach {base}: "), failed)
|
|
|
|
|
|
class Dm(unittest.TestCase):
|
|
def home_with(self, home: str, text: str) -> pathlib.Path:
|
|
folder = pathlib.Path(home, ".claude")
|
|
folder.mkdir()
|
|
return env_file(str(folder), text)
|
|
|
|
def test_sends_through_the_env_file_under_home(self):
|
|
with tempfile.TemporaryDirectory() as home:
|
|
self.home_with(home, "MATTERMOST_URL=https://chat.example\nMATTERMOST_TOKEN=secret-token\nMATTERMOST_RECIPIENT=lilleman\n")
|
|
server = mattermost()
|
|
self.assertIsNone(dm.dm("Which one?", pathlib.Path(home), server))
|
|
self.assertEqual(server.requests[-1], ("POST", "https://chat.example/api/v4/posts", "secret-token", {"channel_id": "channel-id", "message": "Which one?"}))
|
|
|
|
def test_skips_the_dm_on_a_machine_without_the_env_file(self):
|
|
with tempfile.TemporaryDirectory() as home:
|
|
server = mattermost()
|
|
self.assertIsNone(dm.dm("Which one?", pathlib.Path(home), server))
|
|
self.assertEqual(server.requests, [])
|
|
|
|
def test_fails_naming_the_mistake_where_the_env_file_is_there_but_wrong(self):
|
|
with tempfile.TemporaryDirectory() as home:
|
|
path = self.home_with(home, "MATTERMOST_URL=https://chat.example\n")
|
|
self.assertEqual(dm.dm("Which one?", pathlib.Path(home), mattermost()), Failure(f"{path} lacks MATTERMOST_TOKEN and MATTERMOST_RECIPIENT"))
|
|
|
|
|
|
class Main(unittest.TestCase):
|
|
def run_main(self, argv: list[str], stdin: str = "", config: object = CONFIG, server: object = None) -> tuple[int, str]:
|
|
stderr = io.StringIO()
|
|
sent = server or mattermost()
|
|
code = main.main(argv, io.StringIO(stdin), lambda: config, sent, stderr) # type: ignore[arg-type]
|
|
return code, stderr.getvalue()
|
|
|
|
def test_sends_its_argument_or_else_stdin_and_exits_0(self):
|
|
for argv, stdin in ((["Which one?"], ""), ([], "Which one?\n")):
|
|
with self.subTest(argv=argv):
|
|
server = mattermost()
|
|
self.assertEqual(self.run_main(argv, stdin, server=server), (0, ""))
|
|
self.assertEqual(server.requests[-1][3], {"channel_id": "channel-id", "message": "Which one?"})
|
|
|
|
def test_exits_2_on_misuse_naming_it(self):
|
|
missing = Failure("/h/.claude/.env does not exist; it needs MATTERMOST_URL, MATTERMOST_TOKEN and MATTERMOST_RECIPIENT")
|
|
for argv, stdin, config, said in (
|
|
([], " \n", CONFIG, "mattermost-dm: the message is empty\n"),
|
|
(["a", "b"], "", CONFIG, f"mattermost-dm: takes one message, or none to read stdin; got 2 arguments\n{main.USAGE}\n"),
|
|
(["hi"], "", missing, f"mattermost-dm: {missing.reason}\n"),
|
|
):
|
|
with self.subTest(argv=argv, stdin=stdin):
|
|
self.assertEqual(self.run_main(argv, stdin, config), (2, said))
|
|
|
|
def test_exits_1_naming_why_the_send_failed(self):
|
|
server = mattermost()
|
|
server.answers[("GET", "/api/v4/users/me")] = Failure("GET /api/v4/users/me answered 401: Invalid or expired session, please login again.")
|
|
self.assertEqual(self.run_main(["hi"], server=server), (1, "mattermost-dm: GET /api/v4/users/me answered 401: Invalid or expired session, please login again.\n"))
|
|
|
|
def test_the_launcher_prints_help_and_reads_the_env_file_under_home(self):
|
|
with tempfile.TemporaryDirectory() as home:
|
|
env = {**isolated_env(), "HOME": home}
|
|
helped = subprocess.run([sys.executable, str(TOOL), "--help"], capture_output=True, text=True, env=env)
|
|
self.assertEqual((helped.returncode, helped.stdout.splitlines()[0]), (0, main.__doc__.strip().splitlines()[0]))
|
|
sent = subprocess.run([sys.executable, str(TOOL), "hi"], capture_output=True, text=True, env=env)
|
|
self.assertEqual((sent.returncode, sent.stderr), (2, f"mattermost-dm: {home}/.claude/.env does not exist; it needs MATTERMOST_URL, MATTERMOST_TOKEN and MATTERMOST_RECIPIENT\n"))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|