import pathlib import sys import tempfile import unittest import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from notifier import mattermost as dm from failure import Failure 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 HttpJson(unittest.TestCase): def test_sends_the_token_as_a_bearer_and_reads_mattermosts_message_from_an_error(self): with unittest.mock.patch.object(dm.json_request, "http_json", return_value={"id": "post-id"}) as sent: self.assertEqual(dm.http_json("POST", "https://chat.example/api/v4/posts", "secret-token", {"message": "hi"}), {"id": "post-id"}) sent.assert_called_once_with("POST", "https://chat.example/api/v4/posts", "Bearer secret-token", {"message": "hi"}, dm.TIMEOUT, dm.error_message) self.assertEqual(dm.TIMEOUT, 10) def test_reads_mattermosts_message_from_an_error_answer(self): for answer, message in (({"message": "Invalid or expired session."}, "Invalid or expired session."), ({"message": 7}, ""), ({}, ""), (["message"], "")): with self.subTest(answer=answer): self.assertEqual(dm.error_message(answer), message) if __name__ == "__main__": unittest.main()