import json import pathlib import subprocess import sys import tempfile import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from failure import Failure from claude_home.home import unready SETTINGS = { "enabledPlugins": {"code-review@official": True, "frontend-design@official": False, "lsp@other": True}, "extraKnownMarketplaces": {"official": {"source": {"repo": "anthropics/official", "source": "github"}}, "other": {"source": {"repo": "someone/other", "source": "github"}}, "unused": {"source": {"repo": "someone/unused", "source": "github"}}}, "hooks": {"PreToolUse": [{"hooks": [{"command": "{clone}/bin/rule-hook", "type": "command"}]}]}, "tui": "fullscreen", } SIGNED_IN = json.dumps({"loggedIn": True, "authMethod": "claude.ai"}) SIGNED_OUT = json.dumps({"loggedIn": False, "authMethod": "none"}) class Home(unittest.TestCase): def setUp(self) -> None: self.temp = pathlib.Path(tempfile.mkdtemp()) self.addCleanup(subprocess.run, ["rm", "-rf", str(self.temp)]) self.clone = self.temp / "the clone" for folder in ("agents", "rules", "skills"): (self.clone / folder).mkdir(parents=True) (self.clone / "CLAUDE.md").write_text("# The setup's rules\n", encoding="utf-8") (self.clone / "settings.json").write_text(json.dumps(SETTINGS), encoding="utf-8") self.home = self.temp / "share" / "claude-home" self.commit: str | Failure = "1a2b3c\n" self.status = SIGNED_IN # The exit code of each `claude plugin` command, by its last argument; 0 for one not named. self.exits: dict[str, int] = {} self.ran: list[list[str]] = [] def claude(self, args: list[str]) -> subprocess.CompletedProcess[str]: self.ran.append(args) if args == ["auth", "status"]: return subprocess.CompletedProcess(args, 0 if self.status == SIGNED_IN else 1, self.status, "") return subprocess.CompletedProcess(args, self.exits.get(args[-1], 0), "", f"no {args[-1]}\nin the marketplace\n") def unready(self) -> str | None: return unready(self.home, self.clone, self.claude, lambda *args, cwd=None: self.commit if (args, cwd) == (("rev-parse", "HEAD"), str(self.clone)) else Failure(f"unexpected git {args} in {cwd}")) def settings(self) -> dict[str, object]: read: dict[str, object] = json.loads((self.home / "settings.json").read_text(encoding="utf-8")) return read def test_a_new_home_links_the_clones_instruction_files(self) -> None: self.assertIsNone(self.unready()) for name in ("CLAUDE.md", "agents", "rules", "skills"): self.assertTrue((self.home / name).is_symlink(), name) self.assertEqual((self.home / name).resolve(), (self.clone / name).resolve()) self.assertEqual((self.home / "CLAUDE.md").read_text(encoding="utf-8"), "# The setup's rules\n") def test_the_generated_settings_name_the_clone_quoted_for_a_shell_and_leave_the_tracked_file_alone(self) -> None: self.unready() self.assertEqual(self.settings()["hooks"], {"PreToolUse": [{"hooks": [{"command": f"'{self.clone}'/bin/rule-hook", "type": "command"}]}]}) self.assertEqual(self.settings()["tui"], "fullscreen") self.assertEqual(json.loads((self.clone / "settings.json").read_text(encoding="utf-8")), SETTINGS) def test_it_adds_each_enabled_plugins_marketplace_then_installs_each_enabled_plugin(self) -> None: self.unready() self.assertEqual(self.ran, [ ["plugin", "marketplace", "add", "anthropics/official"], ["plugin", "marketplace", "add", "someone/other"], ["plugin", "install", "code-review@official"], ["plugin", "install", "lsp@other"], ["auth", "status"], ]) def test_a_clone_that_enables_no_plugin_installs_none(self) -> None: (self.clone / "settings.json").write_text('{"tui": "fullscreen"}', encoding="utf-8") self.assertIsNone(self.unready()) self.assertEqual(self.ran, [["auth", "status"]]) def test_the_generated_settings_are_written_for_a_person_to_read(self) -> None: (self.clone / "settings.json").write_text('{"tui": "fullscreen", "env": {"A": "1"}}', encoding="utf-8") self.unready() self.assertEqual((self.home / "settings.json").read_text(encoding="utf-8"), '{\n "env": {\n "A": "1"\n },\n "tui": "fullscreen"\n}\n') def test_a_home_built_from_the_clones_commit_is_left_as_it_is(self) -> None: self.unready() (self.home / "settings.json").write_text('{"model": "opus", "tui": "inline"}', encoding="utf-8") self.ran.clear() self.assertIsNone(self.unready()) self.assertEqual(self.ran, [["auth", "status"]]) self.assertEqual(self.settings(), {"model": "opus", "tui": "inline"}) def test_a_new_commit_refreshes_the_home_and_keeps_the_model_claude_code_wrote(self) -> None: self.unready() (self.home / "settings.json").write_text('{"model": "opus", "tui": "inline"}', encoding="utf-8") (self.clone / "settings.json").write_text(json.dumps({**SETTINGS, "tui": "compact"}), encoding="utf-8") self.commit = "4d5e6f\n" self.ran.clear() self.assertIsNone(self.unready()) self.assertEqual(self.settings()["tui"], "compact") self.assertEqual(self.settings()["model"], "opus") self.assertIn(["plugin", "install", "lsp@other"], self.ran) def test_a_clone_that_moved_refreshes_the_home(self) -> None: self.unready() moved = self.temp / "moved" self.clone.rename(moved) self.clone = moved self.assertIsNone(self.unready()) self.assertEqual((self.home / "rules").resolve(), (moved / "rules").resolve()) def test_a_signed_out_home_says_how_to_sign_in(self) -> None: self.status = SIGNED_OUT self.assertEqual(self.unready(), f"nobody is signed in to the loop's Claude home; run `CLAUDE_CONFIG_DIR={self.home} claude` and type /login there, once") def test_a_status_that_says_nobody_is_signed_in_or_out_quotes_what_claude_said(self) -> None: for stdout, stderr, said in (("", "Error: the settings\nare broken\n", "Error: the settings are broken"), ("Not logged in\n", "", "Not logged in"), ('{"authMethod": "none"}', "", '{"authMethod": "none"}'), ("3", "", "3"), ('{"loggedIn": "yes"}', "", '{"loggedIn": "yes"}'), ("", "", "it printed nothing and exited 1")): with self.subTest(said=said): def claude(args: list[str]) -> subprocess.CompletedProcess[str]: return subprocess.CompletedProcess(args, 1, stdout, stderr) if args == ["auth", "status"] else subprocess.CompletedProcess(args, 0, "", "") reason = unready(self.home, self.clone, claude, lambda *args, cwd=None: "1a2b3c\n") self.assertEqual(reason, f"could not ask claude who is signed in to the loop's Claude home, {self.home}: {said}") def test_a_home_settings_file_that_is_no_json_object_stops_naming_the_file(self) -> None: for written in ('{"model": "o', "3"): with self.subTest(written=written): self.home.mkdir(parents=True, exist_ok=True) (self.home / "settings.json").write_text(written, encoding="utf-8") reason = self.unready() or "" self.assertTrue(reason.startswith(f"could not build the loop's Claude home, {self.home}: {self.home / 'settings.json'} is not a JSON object"), reason) self.assertTrue(reason.endswith("; delete it and run again"), reason) def test_a_plugin_that_does_not_install_stops_and_the_next_run_tries_again(self) -> None: self.exits = {"lsp@other": 1} self.assertEqual(self.unready(), f"could not build the loop's Claude home, {self.home}: claude plugin install lsp@other failed: no lsp@other in the marketplace") self.exits = {} self.ran.clear() self.assertIsNone(self.unready()) self.assertIn(["plugin", "install", "lsp@other"], self.ran) def test_a_clone_whose_commit_git_cannot_tell_stops(self) -> None: self.commit = Failure("not a git repository") self.assertEqual(self.unready(), f"could not build the loop's Claude home, {self.home}: not a git repository") def test_a_file_in_a_links_place_stops(self) -> None: (self.home / "rules").mkdir(parents=True) (self.home / "rules" / "mine.md").write_text("", encoding="utf-8") self.assertIn(f"could not build the loop's Claude home, {self.home}: ", self.unready() or "") self.assertTrue((self.home / "rules" / "mine.md").exists()) def test_a_claude_that_cannot_start_stops(self) -> None: def missing(args: list[str]) -> subprocess.CompletedProcess[str]: raise FileNotFoundError(2, "No such file or directory", "claude") reason = unready(self.home, self.clone, missing, lambda *args, cwd=None: "1a2b3c\n") self.assertEqual(reason, f"could not build the loop's Claude home, {self.home}: [Errno 2] No such file or directory: 'claude'") def test_a_claude_that_is_stopped_after_its_time_stops(self) -> None: def stalled(args: list[str]) -> subprocess.CompletedProcess[str]: raise subprocess.TimeoutExpired(["claude", *args], 600) reason = unready(self.home, self.clone, stalled, lambda *args, cwd=None: "1a2b3c\n") self.assertEqual(reason, f"could not build the loop's Claude home, {self.home}: Command '['claude', 'plugin', 'marketplace', 'add', 'anthropics/official']' timed out after 600 seconds") if __name__ == "__main__": unittest.main()