import contextlib import dataclasses import io import os import pathlib import subprocess import sys import tempfile import typing import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from project_config.doubles import configured from failure import Failure from rest_client.json_request import Http from test_env import isolated_env from project_config.main import located from notifier import main, notify from notifier.test_mattermost import mattermost from project_config.settings import Notifier from notifier.test_slack import Slack from loop_effects.effects import system_effects TOOL = pathlib.Path(__file__).resolve().parents[1] / "notify" MATTERMOST_KEYS = "MATTERMOST_URL=https://chat.example\nMATTERMOST_TOKEN=secret-token\nMATTERMOST_RECIPIENT=lilleman\n" SLACK_KEYS = "SLACK_TOKEN=xoxb-secret\nSLACK_RECIPIENT=U0123ABCD\n" MATTERMOST_POST = ("POST", "https://chat.example/api/v4/posts", "secret-token", {"channel_id": "channel-id", "message": "Which one?"}) SLACK_POST = ("POST", "https://slack.com/api/chat.postMessage", "xoxb-secret", {"channel": "U0123ABCD", "text": "Which one?"}) MISSING_MATTERMOST = "does not exist; it needs MATTERMOST_URL, MATTERMOST_TOKEN and MATTERMOST_RECIPIENT" def through(name: Notifier, http: Http) -> dict[Notifier, notify.Backend[typing.Any]]: """The notifier table with the named backend sending through http.""" return {**notify.BACKENDS, name: dataclasses.replace(notify.BACKENDS[name], http=http)} class Project(unittest.TestCase): """A home with a git checkout that a config names; `folder` is the config's folder.""" def setUp(self) -> None: made = tempfile.TemporaryDirectory() self.addCleanup(made.cleanup) self.home = pathlib.Path(made.name).resolve() self.checkout = self.home / "code" / "proj" self.checkout.mkdir(parents=True) self.folder = configured(self, self.checkout, home=self.home) def name_notifier(self, notifier: str | None, keys: str | None = None) -> pathlib.Path: """Makes the config name ~/.claude-projects/proj.env as its env file, and the notifier where there is one; the file holds keys where that is not None.""" with (self.folder / "config.toml").open("a") as config: config.write('env-file = "~/.claude-projects/proj.env"\n' + (f'notifier = "{notifier}"\n' if notifier else "")) path = self.home / ".claude-projects" / "proj.env" if keys is not None: path.write_text(keys) path.chmod(0o600) return path class Notify(Project): def test_sends_through_mattermost_where_the_config_names_it(self): self.name_notifier("mattermost", MATTERMOST_KEYS) server = mattermost() self.assertIsNone(notify.notify("Which one?", str(self.checkout), self.home, through("mattermost", server))) self.assertEqual(server.requests[-1], MATTERMOST_POST) def test_sends_through_slack_where_the_config_names_it(self): self.name_notifier("slack", SLACK_KEYS) slack = Slack({"ok": True}) self.assertIsNone(notify.notify("Which one?", str(self.checkout), self.home, through("slack", slack))) self.assertEqual(slack.requests, [SLACK_POST]) def test_loop_claudes_dm_goes_through_the_notifier_for_the_project_holding_the_current_directory(self): self.name_notifier("slack", SLACK_KEYS) slack = Slack({"ok": True}) with contextlib.chdir(self.checkout): self.assertIsNone(system_effects(self.home, os.environ, through("slack", slack)).dm("Which one?", None)) self.assertEqual(slack.requests, [SLACK_POST]) def test_a_dm_that_names_a_directory_goes_through_the_notifier_for_the_project_holding_it_from_any_current_directory(self): self.name_notifier("slack", SLACK_KEYS) slack = Slack({"ok": True}) with contextlib.chdir(self.home): self.assertIsNone(system_effects(self.home, os.environ, through("slack", slack)).dm("Which one?", str(self.checkout))) self.assertEqual(slack.requests, [SLACK_POST]) def test_skips_the_notice_for_a_project_that_names_no_notifier_even_where_its_env_file_holds_the_keys(self): self.name_notifier(None, MATTERMOST_KEYS) server = mattermost() self.assertIsNone(notify.notify("Which one?", str(self.checkout), self.home, through("mattermost", server))) self.assertEqual(server.requests, []) def test_skips_the_notice_where_no_config_names_the_checkout_since_loop_claude_stops_on_that_itself(self): other = self.home / "code" / "other" other.mkdir() subprocess.run(["git", "init", "--quiet", str(other)], check=True, env=isolated_env()) server = mattermost() self.assertIsNone(notify.notify("Which one?", str(other), self.home, through("mattermost", server))) self.assertEqual(server.requests, []) def test_fails_naming_the_file_or_the_key_where_the_env_file_is_missing_or_wrong(self): path = self.name_notifier("slack") self.assertEqual(notify.notify("hi", str(self.checkout), self.home, through("slack", Slack({"ok": True}))), Failure(f"{path} does not exist; it needs SLACK_TOKEN and SLACK_RECIPIENT")) path.write_text("SLACK_TOKEN=xoxb-secret\n") path.chmod(0o600) self.assertEqual(notify.notify("hi", str(self.checkout), self.home, through("slack", Slack({"ok": True}))), Failure(f"{path} lacks SLACK_RECIPIENT")) def test_the_failure_for_an_unreachable_server_names_the_server_and_not_the_token(self): self.name_notifier("mattermost", MATTERMOST_KEYS.replace("https://chat.example", "https://127.0.0.1:1")) failed = notify.notify("Which one?", str(self.checkout), self.home, notify.BACKENDS) assert isinstance(failed, Failure), failed self.assertIn("cannot reach https://127.0.0.1:1", failed.reason) self.assertNotIn("secret-token", failed.reason) def test_sender_in_fails_for_an_env_file_that_no_notifier_reads(self): self.name_notifier(None, MATTERMOST_KEYS) failed = notify.sender_in(str(self.checkout), self.home, notify.BACKENDS) assert isinstance(failed, Failure), failed self.assertIn("sets no `notifier`", failed.reason) def test_sender_of_names_the_missing_env_file_for_a_config_built_by_hand_with_a_notifier_and_none(self): self.name_notifier("slack", SLACK_KEYS) project = located(str(self.checkout), self.home) assert not isinstance(project, Failure), project failed = notify.sender_of(dataclasses.replace(project, env_file=None), notify.BACKENDS) self.assertEqual(failed, Failure(f"{self.folder / 'config.toml'} sets `notifier` but no `env-file`, the file that holds its credentials")) def test_sender_in_fails_with_the_configs_reason_where_no_config_names_the_checkout(self): other = self.home / "code" / "other" other.mkdir() subprocess.run(["git", "init", "--quiet", str(other)], check=True, env=isolated_env()) self.assertIsInstance(notify.sender_in(str(other), self.home, notify.BACKENDS), Failure) def test_sender_in_names_the_settings_to_add_where_the_config_names_no_notifier(self): failed = notify.sender_in(str(self.checkout), self.home, notify.BACKENDS) assert isinstance(failed, Failure), failed self.assertEqual(failed.reason, f"{self.folder / 'config.toml'} sets no `notifier`; set `notifier` to mattermost or slack, and `env-file` to the file that holds that service's keys (mattermost: MATTERMOST_URL, MATTERMOST_TOKEN, MATTERMOST_RECIPIENT; slack: SLACK_TOKEN, SLACK_RECIPIENT)") class Main(Project): def run_main(self, argv: list[str], stdin: str = "", sender: object = None) -> tuple[int, str]: stderr = io.StringIO() ready = sender or (lambda message: None) code = main.main(argv, io.StringIO(stdin), lambda: ready, 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): sent: list[str] = [] self.assertEqual(self.run_main(argv, stdin, lambda message: sent.append(message)), (0, "")) self.assertEqual(sent, ["Which one?"]) def test_prints_help_for_either_help_flag_whatever_follows_it(self): for argv in (["-h"], ["--help"], ["--help", "extra"]): with self.subTest(argv=argv), contextlib.redirect_stdout(io.StringIO()) as printed: self.assertEqual(self.run_main(argv), (0, "")) self.assertEqual(printed.getvalue(), main.__doc__.strip() + "\n") def test_exits_2_on_misuse_naming_it(self): for argv, stdin, said in ( ([], " \n", "notify: the message is empty\n"), (["a", "b"], "", f"notify: takes one message, or none to read stdin; got 2 arguments\n{main.USAGE}\n"), ): with self.subTest(argv=argv, stdin=stdin): self.assertEqual(self.run_main(argv, stdin), (2, said)) def test_exits_2_naming_the_config_fault_where_there_is_no_sender(self): stderr = io.StringIO() self.assertEqual(main.main(["hi"], io.StringIO(), lambda: Failure("/h/proj.env does not exist"), stderr), 2) # type: ignore[arg-type] self.assertEqual(stderr.getvalue(), "notify: /h/proj.env does not exist\n") def test_exits_1_naming_why_the_send_failed(self): failed = Failure("POST /api/chat.postMessage refused the message: invalid_auth") self.assertEqual(self.run_main(["hi"], sender=lambda message: failed), (1, f"notify: {failed.reason}\n")) def test_the_launcher_prints_help_and_reads_the_env_file_the_projects_config_names(self): env = {**isolated_env(), "HOME": str(self.home)} helped = subprocess.run([sys.executable, str(TOOL), "--help"], capture_output=True, text=True, env=env, cwd=self.checkout) self.assertEqual((helped.returncode, helped.stdout.splitlines()[0]), (0, main.__doc__.strip().splitlines()[0])) path = self.name_notifier("mattermost") sent = subprocess.run([sys.executable, str(TOOL), "hi"], capture_output=True, text=True, env=env, cwd=self.checkout) self.assertEqual((sent.returncode, sent.stderr), (2, f"notify: {path} {MISSING_MATTERMOST}\n")) if __name__ == "__main__": unittest.main()