250 lines
12 KiB
Python
250 lines
12 KiB
Python
import os
|
|
import pathlib
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import unittest
|
|
import unittest.mock
|
|
|
|
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
|
|
|
from failure import Failure
|
|
from project_config.settings import held, load, ProjectConfig, SETTINGS, Unnamed
|
|
from test_env import isolated_env
|
|
from project_config.main import located
|
|
|
|
TOOL = pathlib.Path(__file__).resolve().parents[1] / "project-config"
|
|
|
|
CLIENT = """checkout = "~/code/acme-billing"
|
|
plan = "folder:todo.md"
|
|
working-rules = "folder:AGENTS.md"
|
|
decisions = "folder:docs/decisions.md"
|
|
score-anchors = "folder:docs/score-anchors.md"
|
|
comprehension-history = "folder:docs/comprehension-history.md"
|
|
reading-cost = "folder:docs/reading-cost.md"
|
|
changelog = "checkout:CHANGELOG.md"
|
|
goals-and-audience = "folder:goals.md"
|
|
principles = "~/.claude/principles"
|
|
"""
|
|
|
|
|
|
def write_config(home: pathlib.Path, checkout: pathlib.Path, goals: str = "checkout:README.md") -> pathlib.Path:
|
|
"""A config under home that names checkout, every setting inside it but goals-and-audience; for the tests of each tool that reads the config."""
|
|
folder = home / ".claude-projects" / checkout.name
|
|
folder.mkdir(parents=True, exist_ok=True)
|
|
(folder / "config.toml").write_text(CLIENT.replace('"~/code/acme-billing"', f'"{checkout}"').replace('"folder:', '"checkout:').replace('"checkout:goals.md"', f'"{goals}"'), encoding="utf-8")
|
|
return folder
|
|
|
|
|
|
def configured(test: unittest.TestCase, checkout: pathlib.Path, goals: str = "checkout:README.md", home: pathlib.Path | None = None) -> pathlib.Path:
|
|
"""Makes checkout a git checkout that a config names, under home, else a HOME of its own, for the rest of the test; the config's folder."""
|
|
subprocess.run(["git", "init", "--quiet", str(checkout)], check=True, env=isolated_env())
|
|
if home is None:
|
|
made = tempfile.TemporaryDirectory()
|
|
test.addCleanup(made.cleanup)
|
|
home = pathlib.Path(made.name)
|
|
patched = unittest.mock.patch.dict(os.environ, {"HOME": str(home)})
|
|
patched.start()
|
|
test.addCleanup(patched.stop)
|
|
return write_config(home, checkout, goals)
|
|
|
|
|
|
class ConfigCase(unittest.TestCase):
|
|
def setUp(self) -> None:
|
|
made = tempfile.TemporaryDirectory()
|
|
self.addCleanup(made.cleanup)
|
|
self.home = pathlib.Path(made.name).resolve()
|
|
self.checkout = self.home / "code" / "acme-billing"
|
|
self.checkout.mkdir(parents=True)
|
|
|
|
def write(self, key: str, text: str) -> pathlib.Path:
|
|
folder = self.home / ".claude-projects" / key
|
|
folder.mkdir(parents=True)
|
|
(folder / "config.toml").write_text(text, encoding="utf-8")
|
|
return folder
|
|
|
|
|
|
class LoadTest(ConfigCase):
|
|
def failure(self, top: pathlib.Path | None = None) -> str:
|
|
found = load(top or self.checkout, self.checkout, self.home)
|
|
assert isinstance(found, Failure), found
|
|
return found.reason
|
|
|
|
def test_resolves_each_setting_by_its_prefix(self) -> None:
|
|
folder = self.write("acme", CLIENT)
|
|
self.write("other", CLIENT.replace("acme-billing", "other"))
|
|
found = load(self.checkout, self.checkout, self.home)
|
|
assert isinstance(found, ProjectConfig), found
|
|
self.assertEqual((found.key, found.folder), ("acme", folder))
|
|
self.assertEqual(found.paths["plan"], folder / "todo.md")
|
|
self.assertEqual(found.paths["decisions"], folder / "docs" / "decisions.md")
|
|
self.assertEqual(found.paths["changelog"], self.checkout / "CHANGELOG.md")
|
|
self.assertEqual(found.paths["principles"], self.home / ".claude" / "principles")
|
|
self.assertEqual(tuple(found.paths), SETTINGS)
|
|
|
|
def test_a_worktree_finds_the_main_checkouts_config_and_reads_its_own_files(self) -> None:
|
|
self.write("acme", CLIENT)
|
|
worktree = self.home / "code" / "acme-billing-item-3"
|
|
found = load(worktree, self.checkout, self.home)
|
|
assert isinstance(found, ProjectConfig), found
|
|
self.assertEqual(found.paths["changelog"], worktree / "CHANGELOG.md")
|
|
|
|
def test_names_a_file_in_the_checkout_as_git_does_and_none_outside_it(self) -> None:
|
|
self.write("acme", CLIENT.replace("folder:docs/decisions.md", "checkout:project/decisions.md"))
|
|
worktree = self.home / "code" / "acme-billing-item-3"
|
|
found = load(worktree, self.checkout, self.home)
|
|
assert isinstance(found, ProjectConfig), found
|
|
self.assertEqual(found.tracked("changelog"), "CHANGELOG.md")
|
|
self.assertEqual(found.tracked("decisions"), "project/decisions.md")
|
|
self.assertIsNone(found.tracked("plan"), "the config's folder is outside the checkout")
|
|
|
|
def test_an_absolute_checkout_and_path_are_taken_as_written(self) -> None:
|
|
self.write("acme", CLIENT.replace("~/code/acme-billing", str(self.checkout)).replace("~/.claude/principles", "/srv/principles"))
|
|
found = load(self.checkout, self.checkout, self.home)
|
|
assert isinstance(found, ProjectConfig), found
|
|
self.assertEqual(found.paths["principles"], pathlib.Path("/srv/principles"))
|
|
|
|
def test_a_checkout_reached_through_a_symlink_or_dots_finds_its_config(self) -> None:
|
|
self.write("acme", CLIENT)
|
|
(self.home / "work").symlink_to(self.home / "code")
|
|
for case, main in {"a symlink": self.home / "work" / "acme-billing", "dots": self.home / "code" / "other" / ".." / "acme-billing"}.items():
|
|
with self.subTest(case=case):
|
|
self.assertIsInstance(load(main, main, self.home), ProjectConfig)
|
|
|
|
def test_no_config_fails_naming_the_checkout_and_the_file_to_write(self) -> None:
|
|
for write_other in (False, True):
|
|
with self.subTest(write_other=write_other):
|
|
if write_other:
|
|
self.write("other", CLIENT.replace("acme-billing", "other"))
|
|
reason = self.failure()
|
|
self.assertIn(str(self.checkout), reason)
|
|
self.assertIn("~/.claude-projects/<key>/config.toml", reason)
|
|
|
|
def test_tells_a_checkout_no_config_names_from_one_whose_config_is_faulty(self) -> None:
|
|
self.assertIsInstance(load(self.checkout, self.checkout, self.home), Unnamed)
|
|
self.assertIsInstance(located(str(self.checkout), self.home), Unnamed, "a folder that is no checkout has no config either")
|
|
self.write("acme", CLIENT.replace('plan = "folder:todo.md"\n', ""))
|
|
self.assertNotIsInstance(load(self.checkout, self.checkout, self.home), Unnamed)
|
|
self.assertIn("`plan` is missing", self.failure())
|
|
|
|
def test_every_missing_setting_is_named(self) -> None:
|
|
kept = "".join(line + "\n" for line in CLIENT.splitlines() if not line.startswith(("plan", "changelog", "principles")))
|
|
self.write("acme", kept)
|
|
reason = self.failure()
|
|
for name in ("plan", "changelog", "principles"):
|
|
with self.subTest(name=name):
|
|
self.assertIn(f"`{name}` is missing", reason)
|
|
self.assertNotIn("`decisions` is", reason)
|
|
self.assertIn("acme/config.toml", reason)
|
|
|
|
def test_every_fault_in_one_config_is_named_together(self) -> None:
|
|
cases = {
|
|
"an unknown setting": ('readme = "checkout:README.md"\n', "`readme`"),
|
|
"a path with no prefix": ('plan = "todo.md"\n', "`plan`"),
|
|
"a path with an unknown prefix": ('plan = "repo:todo.md"\n', "`plan`"),
|
|
"a value that is not text": ("plan = 3\n", "`plan`"),
|
|
"a path that leaves the folder": ('plan = "folder:../other/todo.md"\n', "`plan`"),
|
|
"a path that leaves the checkout": ('plan = "checkout:../todo.md"\n', "`plan`"),
|
|
"an empty path": ('plan = "folder:"\n', "`plan`"),
|
|
}
|
|
for case, (line, named) in cases.items():
|
|
with self.subTest(case=case), tempfile.TemporaryDirectory() as made:
|
|
self.home = pathlib.Path(made).resolve()
|
|
self.checkout = self.home / "code" / "acme-billing"
|
|
text = "".join(kept + "\n" for kept in CLIENT.splitlines() if not kept.startswith(("plan", "decisions")))
|
|
self.write("acme", text + line)
|
|
reason = self.failure()
|
|
self.assertIn(named, reason)
|
|
self.assertIn("`decisions`", reason)
|
|
|
|
def test_two_configs_naming_one_checkout_fail_naming_both(self) -> None:
|
|
self.write("acme", CLIENT)
|
|
self.write("acme-copy", CLIENT)
|
|
reason = self.failure()
|
|
self.assertIn("acme/config.toml", reason)
|
|
self.assertIn("acme-copy/config.toml", reason)
|
|
|
|
def test_a_config_that_cannot_be_read_fails_whichever_checkout_asks(self) -> None:
|
|
cases = {"not TOML": "checkout = ", "no checkout": 'plan = "folder:todo.md"\n', "a checkout that is not text": "checkout = 3\n", "a relative checkout": 'checkout = "code/acme"\n'}
|
|
for case, text in cases.items():
|
|
with self.subTest(case=case), tempfile.TemporaryDirectory() as made:
|
|
self.home = pathlib.Path(made).resolve()
|
|
self.write("acme", CLIENT)
|
|
self.write("broken", text)
|
|
self.assertIn("broken/config.toml", self.failure())
|
|
|
|
def test_a_folder_with_no_config_is_skipped(self) -> None:
|
|
self.write("acme", CLIENT)
|
|
(self.home / ".claude-projects" / "notes").mkdir()
|
|
self.assertIsInstance(load(self.checkout, self.checkout, self.home), ProjectConfig)
|
|
|
|
|
|
class HeldTest(ConfigCase):
|
|
def test_a_configs_folder_holds_its_config_as_the_main_checkout_reads_it(self) -> None:
|
|
folder = self.write("acme", CLIENT)
|
|
found = held(folder, self.home)
|
|
assert isinstance(found, ProjectConfig), found
|
|
self.assertEqual((found.folder, found.top, found.paths["plan"]), (folder, self.checkout, folder / "todo.md"), "the config's ~/ checkout read under home")
|
|
|
|
def test_a_folder_holds_no_config_unless_it_is_under_the_projects_folder_and_has_one(self) -> None:
|
|
self.assertIsNone(held(self.home / ".claude-projects" / "empty", self.home), "no config.toml")
|
|
elsewhere = self.home / "code" / "acme"
|
|
elsewhere.mkdir()
|
|
(elsewhere / "config.toml").write_text(CLIENT, encoding="utf-8")
|
|
self.assertIsNone(held(elsewhere, self.home), "a config.toml outside ~/.claude-projects/")
|
|
|
|
def test_a_configs_folder_reached_through_a_symlink_holds_its_config(self) -> None:
|
|
target = self.home / "kept" / "acme"
|
|
target.mkdir(parents=True)
|
|
(target / "config.toml").write_text(CLIENT, encoding="utf-8")
|
|
(self.home / ".claude-projects").mkdir()
|
|
(self.home / ".claude-projects" / "acme").symlink_to(target)
|
|
self.assertIsInstance(held(target, self.home), ProjectConfig, "git names the folder by its resolved path")
|
|
|
|
|
|
class ToolTest(ConfigCase):
|
|
def run_tool(self, *args: str, cwd: pathlib.Path | None = None) -> subprocess.CompletedProcess[str]:
|
|
return subprocess.run([sys.executable, str(TOOL), *args], cwd=cwd or self.checkout, env={**isolated_env(), "HOME": str(self.home)}, capture_output=True, text=True)
|
|
|
|
def setUp(self) -> None:
|
|
super().setUp()
|
|
subprocess.run(["git", "init", "-q", str(self.checkout)], check=True, env=isolated_env())
|
|
|
|
def test_prints_every_setting_or_the_one_asked_for(self) -> None:
|
|
folder = self.write("acme", CLIENT)
|
|
everything = self.run_tool()
|
|
self.assertEqual((everything.returncode, everything.stderr), (0, ""))
|
|
self.assertEqual(everything.stdout.splitlines()[0], f"plan: {folder}/todo.md")
|
|
self.assertEqual(tuple(line.split(": ")[0] for line in everything.stdout.splitlines()), SETTINGS)
|
|
(self.checkout / "src").mkdir()
|
|
one = self.run_tool("changelog", cwd=self.checkout / "src")
|
|
self.assertEqual((one.returncode, one.stdout), (0, f"{self.checkout}/CHANGELOG.md\n"))
|
|
|
|
def test_fails_on_stderr(self) -> None:
|
|
cases = {"no config": ((), "no config names the checkout"), "an unknown setting": (("readme",), "usage:"), "two arguments": (("plan", "changelog"), "usage:")}
|
|
for case, (args, said) in cases.items():
|
|
with self.subTest(case=case):
|
|
ran = self.run_tool(*args)
|
|
self.assertEqual((ran.returncode, ran.stdout), (1, ""))
|
|
self.assertIn(said, ran.stderr)
|
|
|
|
def test_help_shows_a_config(self) -> None:
|
|
for flag in ("-h", "--help"):
|
|
with self.subTest(flag=flag):
|
|
ran = self.run_tool(flag)
|
|
self.assertEqual(ran.returncode, 0)
|
|
self.assertIn('plan = "folder:todo.md"', ran.stdout)
|
|
|
|
def test_a_linked_worktree_finds_the_config_and_prints_its_own_files(self) -> None:
|
|
self.write("acme", CLIENT)
|
|
worktree = self.home / "code" / "acme-billing-item-3"
|
|
git = ["git", "-C", str(self.checkout), "-c", "user.name=t", "-c", "user.email=t@example.com"]
|
|
subprocess.run([*git, "commit", "-q", "--allow-empty", "-m", "first"], check=True, env=isolated_env())
|
|
subprocess.run([*git, "worktree", "add", "-q", str(worktree)], check=True, env=isolated_env())
|
|
ran = self.run_tool("changelog", cwd=worktree)
|
|
self.assertEqual((ran.returncode, ran.stdout), (0, f"{worktree}/CHANGELOG.md\n"))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|